Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare list values with dictionary keys and make a new dictionary of it using python

I have a list like this:

lis = ['Date', 'Product', 'Price']

I want to compare it with:

dict = {'Date' : '2013-05-01', 'Salary' : '$5000', 'Product' : 'Toys', 'Price' : '$10', 'Salesman' : 'Smith'}

I want to compare each item of list with keys of dictionary and make a new dictionary.
What I have tried is:

n = {}
for k,v in dict.items():
    for i in lis:
        if i==k:
            n[k] = v

Output:

n = {'Date' : '2013-05-01', 'Product' : 'Toys', 'Price' : '$10'}

This works but I want to do it through generators - can someone help me do that?

like image 847
MHS Avatar asked Mar 13 '13 12:03

MHS


1 Answers

Treat lis as a set instead, so you can use dictionary views and an intersection:

# python 2.7:
n = {k: d[k] for k in d.viewkeys() & set(lis)}

# python 3:
n = {k: d[k] for k in d.keys() & set(lis)}

Or you could use a simple dict comprehension with a in test against d:

# python 2.6 or older:
n = dict((k, d[k]) for k in lis if k in d)

# python 2.7 and up:
n = {k: d[k] for k in lis if k in d}

This presumes that not all values in lis are going to be in d; the if k in d test can be dropped if they are always going to be present.

For your specific case, the second form is quite a lot faster:

>>> from timeit import timeit
>>> timeit("{k: d[k] for k in d.viewkeys() & s}", 'from __main__ import d, lis; s=set(lis)')
2.156520128250122
>>> timeit("{k: d[k] for k in lis if k in d}", 'from __main__ import d, lis')
0.9401540756225586
like image 144
Martijn Pieters Avatar answered Sep 27 '22 20:09

Martijn Pieters