[英]Transfer a key and respective value from one dict to another
I have a main dict with a certain number of keys ei我有一个带有一定数量键 ei 的主字典
dict1 = {NAME: John, Second_Name: Doe}
I have a series of this dicts and all of them are inside a list.我有一系列这样的字典,它们都在一个列表中。 Is there a way to loop through this list and create a list with dictionaries with, for example, only the key NAME and respective value?有没有办法遍历这个列表并创建一个包含字典的列表,例如,只有键 NAME 和相应的值? Is there a straightforward way to do this?有没有一种直接的方法来做到这一点?
PS: I'm using dict1 as an example as in my program I'm working with dicts with a lot more keys. PS:我使用 dict1 作为示例,因为在我的程序中,我正在使用更多键的 dicts。
I'd use a list comprehension:我会使用列表理解:
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]
You can use a list comprehension :您可以使用列表理解:
[{'NAME': d['NAME']} for d in dictionaries]
That will raise a KeyError
if NAME
is not found.如果未找到NAME
这将引发KeyError
。 You can use a default instead like this:您可以像这样使用默认值:
[{'NAME': d.get('NAME', 'unknown')} for d in dictionaries]
for each dictionary, d
, in dictionaries
, it creates a dictionary with a single key, NAME
, that has the value of d['NAME']
.对于字典中的每个字典d
,它创建一个具有单个键NAME
dictionaries
,其值为d['NAME']
。
Full disclosure: I don't really know what I'm doing.完全披露:我真的不知道我在做什么。
Extending on @ForeverWintr's answer, to allow the copying of keys which don't necessarily exist, which I think OP was asking for in the comments:扩展@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
]
I've no idea if that k in filter
thing is efficient.我不知道k in filter
的那个k in filter
是否有效。 Maybe there's a better way.也许有更好的方法。 It seems like you'd want to pre-cook filter
into a structure that was more efficient to search.似乎您希望将filter
预煮成一个搜索效率更高的结构。 Maybe another dict?也许另一个字典?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.