如何使用字典键比较列表值并使用python创建新字典 [英] How to compare list values with dictionary keys and make a new dictionary of it using python
问题描述
我有一个这样的列表:
lis = ['Date', 'Product', 'Price']
我想将其与:
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
输出:
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?
推荐答案
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)}
或者您可以将简单的dict理解与针对d
的in
测试一起使用:
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}
这假定不是lis
中的所有值都将在d
中;如果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
这篇关于如何使用字典键比较列表值并使用python创建新字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!