Python 在列表的每个字典中添加一个元素(列表理解)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14071038/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Add an element in each dictionary of a list (list comprehension)
提问by Micka?lG
I have a list of dictionaries, and want to add a key for each element of this list. I tried:
我有一个字典列表,想为这个列表的每个元素添加一个键。我试过:
result = [ item.update({"elem":"value"}) for item in mylist ]
but the update method returns None, so my result list is full of None.
但是 update 方法返回 None,所以我的结果列表全是 None。
result = [ item["elem"]="value" for item in mylist ]
returns a syntax error.
返回一个语法错误。
采纳答案by Jeffrey Theobald
You don't need to worry about constructing a new list of dictionaries, since the references to your updated dictionaries are the same as the references to your old dictionaries:
您无需担心构建新的词典列表,因为对更新词典的引用与对旧词典的引用相同:
for item in mylist:
item.update( {"elem":"value"})
回答by sean
>>> a = [ { 1:1 }, {2:2}, {3:3} ]
>>> for item in a:
... item.update( { "test": "test" } )
...
>>> a
[{'test': 'test', 1: 1}, {'test': 'test', 2: 2}, {'test': 'test', 3: 3}]
You are using a list comprehension incorrectly, the call to item.updatereturns a Nonevalue and thus your newly created list will be full of Nonevalues instead of your expected dictvalues.
您错误地使用了列表理解,调用item.update返回一个None值,因此您新创建的列表将充满None值而不是您的预期dict值。
You need only to loop over the items in the list and update each accordingly, because the list holds references to the dictvalues.
您只需要遍历列表中的项目并相应地更新每个项目,因为列表包含对dict值的引用。
回答by Martijn Pieters
Either do not use a list comprehension, or return a newdict based on the original dict plus the new key:
要么不使用列表解析,或返回一个新的在原有基础上加字典的新密钥字典:
[dict(list(item.items()) + [("elem", "value")]) for item in mylist]
回答by vk1011
If you want to use list comprehension, there's a great answer here: https://stackoverflow.com/a/3197365/4403872
如果你想使用列表理解,这里有一个很好的答案:https: //stackoverflow.com/a/3197365/4403872
In your case, it would be like this:
在你的情况下,它会是这样的:
result = [dict(item, **{'elem':'value'}) for item in myList]
Eg.:
例如。:
myList = [{'a': 'A'}, {'b': 'B'}, {'c': 'C', 'cc': 'CC'}]
Then use either
然后使用
result = [dict(item, **{'elem':'value'}) for item in myList]
or
或者
result = [dict(item, elem='value') for item in myList]
Finally,
最后,
>>> result
[{'a': 'A', 'elem': 'value'},
{'b': 'B', 'elem': 'value'},
{'c': 'C', 'cc': 'CC', 'elem': 'value'}]
回答by Asive Dlaba
You can use map.
您可以使用地图。
result = map(lambda item: dict(item, elem='value'), myList)
If you already have the list of lements you can do:
如果您已经有了元素列表,您可以执行以下操作:
#elements = ['value'] * len(myList)
result = map(lambda item: dict(item[0], elem=item[1]),zip(myList,elements))
then you have the results
然后你有结果
回答by matharumanpreet00
@vk1011's answer is good and can be extended with the spread operator concisely and new dictionary objects are an added benefit
@vk1011 的回答很好,可以用扩展运算符简洁地扩展,新的字典对象是一个额外的好处
To override any existing key's value with the new one you can put the spread operator before the new item
result = [{**item, 'elem':'value'} for item in myList]To override the new entry's value with an existing one, use the spread operator after the new item
result = [{'elem':'value', **item} for item in myList]
要使用新键覆盖任何现有键的值,您可以将扩展运算符放在新项之前
result = [{**item, 'elem':'value'} for item in myList]要使用现有条目覆盖新条目的值,请在新条目之后使用扩展运算符
result = [{'elem':'value', **item} for item in myList]
Both methods will give a list of dictionary objects including the new item
这两种方法都会给出一个字典对象列表,包括新项目

