问题
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?
回答1:
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
回答2:
filtered_dict = dict((k, original_dict[k]) for k in lis if k in original_dict)
Or if you have 2.7+:
filtered_dict = {k: original_dict[k] for k in lis if k in original_dict}
If you want to use a generator:
item_generator = ((k, original_dict[k]) for k in lis if k in original_dict)
The generator will yield (key, value)
pairs.
来源:https://stackoverflow.com/questions/15385308/how-to-compare-list-values-with-dictionary-keys-and-make-a-new-dictionary-of-it