[英]how to add keys from an existing dictionary to a new dictionary
我有一本看起來像這樣的字典:
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]}
到目前為止,我已經這樣做了:我試圖刪除字典 pris 中不需要的鍵,但我得到了所有我不想要的元素。 我嘗試使用 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]}
有人能幫我嗎?
試試這個:
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}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.