Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing dictionaries in Python

Given two dictionaries, d1 and d2, and an integer l, I want to find all keys k in d1 such that either d2[k]<l or k not in l. I want to output the keys and the corresponding values in d2, except if d2 does not contain the key, I want to print 0. For instance, if d1 is

a: 1
b: 1
c: 1
d: 1

and d2 is

a: 90
b: 89
x: 45
d: 90

and l is 90, the output would be (possibly in a different order)

b 89
c 0

What is the best way to do this in Python? I am just starting to learn the language, and so far this is what I have:

for k in d1.keys():
    if k not in d2:
        print k, 0
    else:
        if d2[k]<l:
            print k, d2[k]

This works of course (unless I have a typo), but it seems to me that there would be a more pythonic way of doing it.

like image 338
user44511 Avatar asked Jan 12 '09 03:01

user44511


1 Answers

Yours is actually fine -- you could simplify it to

for k in d1:
    if d2.get(k, 0) < l:
       print k, d2.get(k, 0)

which is (to me) pythonic, and is pretty much a direct "translation" into code of your description.

If you want to avoid the double lookup, you could do

for k in d1:
    val = d2.get(k, 0)
    if val < l:
        print k, val
like image 68
dF. Avatar answered Sep 22 '22 20:09

dF.