Python 3 - How to convert dictionary to a counter ?

I have  a list (mylist)  which I iterate - each iteration tests the list value against two dictionaries. It can happen that the  end_cnt dictionary may not contain the mylist item being iterated and then returns an error. If I were to convert end_cnt to a counter  it would return a 0, which is exactly what I want.  The code is attached and this is the error message when I run it.

I thought it would be easy to convert a dictionary to a counter, but cant find anything on it .  Can someone show me how to do this, or suggest an alternative approach ?

many thanks

<H3>Traceback (most recent call last):</H3>
<PRE>  File &quot;C:\xampp2\htdocs\OFFICE_15\adding_dicts.cgi&quot;, line 43, in &lt;module&gt;
    if drop_cnt[each] == 2 and end_cnt[each] == 0:
<B>KeyError: 20

Open in new window

import cgi,cgitb
import mysql.connector as conn
import collections
import datetime
import json
import traceback
def htmlTop():
        <!DOCTYPE html>
        <html lang="en">
                #<meta http-equiv="Content-Type" content="text/html;charset=iso-8859-1">
                <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
                <title> My Server-side template</title>

def htmlTail():
    print(""" its done</body>

def connectDB():
    db=conn.connect(host='localhost' ,user='root' ,passwd='844cheminduplan' ,db='office')
    cursor = db.cursor()
    return db, cursor 

#main program
if __name__== "__main__":
        mylist = [10,9,20]
        drop_cnt = ({10: 1, 9: 1, 20: 2})
        end_cnt = ({9: 2, 11: 2, 10: 1, 12: 1}) 
        for each in mylist:
            if drop_cnt[each] == 1 and end_cnt[each] == 2:
                print(each, "no rebate")
            if drop_cnt[each] == 1 and end_cnt[each] == 1:
                print(each, "rebate")               
            if drop_cnt[each] == 2 and end_cnt[each] == 0: #THIS IS THE PROBLEM
                print(each, "rebatex2")            

Open in new window

Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

if I understand correctly you'd like to return the value from the dict if the key exists and otherwise a zero, right?

To get a default value from a dict in case the key doesn't exist use get()

value = yourdict.get(key, default_value)

Your changed code would look like.

        mylist = [10,9,20]
        drop_cnt = ({10: 1, 9: 1, 20: 2})
        end_cnt = ({9: 2, 11: 2, 10: 1, 12: 1})  
        drop_defaut_value = 0
        end_default_value = 0
        for each in mylist:
            drop_value = drop_cnt.get(each, drop_default_value)
            end_value = end_cnt.get(each, end_default_value)

            if drop_value == 1 and end_value == 2:
                print(each, "no rebate")
            elif drop_value == 1 and end_value == 1:
                print(each, "rebate")               
            elif drop_value == 2 and end_value == 0: #THIS IS THE PROBLEM
                print(each, "rebatex2")
               print("not sure what to do here")

Open in new window

Just a general suggestion for future questions:
It might be a good idea to make you example code as small as possible, such, that the experts don't have
to read through code lines, that are irrelevant to the problem.
In your case (if I understood the question correctly) html_top / html_tail and connect_db are irrelevant for the given problem.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
jameskaneAuthor Commented:
Thanks very much, that works and now I better understand the relationship between dictionaries and collections.

Noted your point about the info supplied. Reason it happened is that I  use a standard template when trying out some new code - lot of the time this involves database connections.  I'll remember to strip that out in the future if its not relevant to the problem !

thanks again
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.