我有一个像这样的字典:
pris = {'äpplen': [12,13,15,16,17], 'bananer': [14,17,18,19], 'citroner': [20,13,14,15,16], 'hallon': [23,34,45,46,57], 'kokos': [12,45,67,89]}
一个另一个:
t={'äpplen', 'bananer', 'hallon'}
我要做的是创建一个只包含t中的元素的新字典。
New_dictionary= {'äpplen': [12,13,15,16,17], 'bananer': [14,17,18,19], 'hallon': [23,34,45,46,57]}
到目前为止,我已经这样做了:我试图删除字典列表中不需要的键,但是我得到了所有我不想要的元素。我尝试使用append等,但它不起作用。
for e in t:
if e is not pris:
del pris[e]
print(pris)
>>> {'citroner': [20, 13, 14, 15, 16], 'kokos': [12, 45, 67, 89]}
有人能帮帮我吗?
try this:
new_d = dict()
for key in t:
if key in pris:
new_d[key] = pris[key]
这是如何在1行
new_d = {key:pris[key] for key in t if key in pris}
试试这个:
new_dict = {}
for e in t:
if e in pris.keys():
new_dict[e] = pris[e]
New_dictionary={k:pris[k] for k in t}