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

限于喜欢 提交于 2020-01-21 03:43:11

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!