You can use tuples as your keys. Instead of '111, A'
try ('111', 'A')
It allows you to easily loop through the dictionary looking for matches to either the first or second key value. Just like what you have, except change the key:
for row in lists:
key = (row[0], row[1])
if key in dictionary:
dictionary[key] += 1
else:
dictionary[key] = 1
#gives
dictionary = {('111', 'A'): 4, ('111', 'B'):10, ('112', 'A'):4}
Now, you're exactly right: you need a variable to store the total, you need to loop through the dictionary, and you need to use conditional statements inside the loop. What exactly are you asking about?
You can loop through the dictionary like this:
for k in d:
print k, d[k]
If you keep your string keys, you will need to extract the two values from each key, which you can do with split
. (No need to do this step if you use tuples):
#with string keys
key_1, key_2 = k.split(',')
You need to test if the first key value matches the desired number, and then you want to print the letter and the value d[k], and update the total variable:
if key_1 == desired:
print key_2, d[k]
total += d[k]
So you can put it together, inside a function like this:
def f(d, desired):
total = 0
for k in d:
key_1, key_2 = k.split(',')
if key_1 == desired:
print key_2, d[k]
total += d[k]
print 'total', total
If you use tuples instead of keys, you can remove the split step, and just use k[0] and k[1] to get the two values:
def f(d, desired):
total = 0
for k in d:
if k[1] == desired:
print k[0], d[k]
total += d[k]
print 'total', total