[英]Transfer a key and respective value from one dict to another
我有一個帶有一定數量鍵 ei 的主字典
dict1 = {NAME: John, Second_Name: Doe}
我有一系列這樣的字典,它們都在一個列表中。 有沒有辦法遍歷這個列表並創建一個包含字典的列表,例如,只有鍵 NAME 和相應的值? 有沒有一種直接的方法來做到這一點?
PS:我使用 dict1 作為示例,因為在我的程序中,我正在使用更多鍵的 dicts。
我會使用列表理解:
list_of_dicts = [
{'NAME': 'John', 'Second_Name': 'Doe'},
{'NAME': 'Tim', 'Second_Name': 'Doh'},
{'NAME': 'Mark', 'Second_Name': 'Dough'},
]
names_only = [{'NAME': d['NAME']} for d in list_of_dicts]
您可以使用列表理解:
[{'NAME': d['NAME']} for d in dictionaries]
如果未找到NAME
這將引發KeyError
。 您可以像這樣使用默認值:
[{'NAME': d.get('NAME', 'unknown')} for d in dictionaries]
對於字典中的每個字典d
,它創建一個具有單個鍵NAME
dictionaries
,其值為d['NAME']
。
完全披露:我真的不知道我在做什么。
擴展@ForeverWintr 的回答,允許復制不一定存在的密鑰,我認為 OP 在評論中要求這樣做:
list_of_dicts = [
{'NAME': 'John', 'Second_Name': 'Doe'},
{'NAME': 'Tim', 'Second_Name': 'Doh'},
{'NAME': 'Mark', 'Second_Name': 'Dough', 'SECRET_HANDSHAKE': True},
]
filter = ['NAME', 'SECRET_HANDSHAKE']
names_only = [{
k: v
for k, v in d.items()
if k in filter
} for d in list_of_dicts
]
我不知道k in filter
的那個k in filter
是否有效。 也許有更好的方法。 似乎您希望將filter
預煮成一個搜索效率更高的結構。 也許另一個字典?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.