在列表的每个字典中添加一个元素(列表理解) [英] Add an element in each dictionary of a list (list comprehension)
本文介绍了在列表的每个字典中添加一个元素(列表理解)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个词典列表,并且想为该列表的每个元素添加一个键. 我试过了:
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 ]
但是update方法返回None,所以我的结果列表中没有None.
but the update method returns None, so my result list is full of None.
result = [ item["elem"]="value" for item in mylist ]
返回语法错误.
推荐答案
您不必担心构造新的词典列表,因为对更新后的词典的引用与对旧词典的引用相同:
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"})
这篇关于在列表的每个字典中添加一个元素(列表理解)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文