[英]How do I add a new key value pair to a list of dictionaries?
Hi new python coder here, let's say I have a list of dictionaries:嗨,这里有新的 python 编码器,假设我有一个字典列表:
data = [{'stat_1': 'name_1', 'stat_2': 10}, {'stat_1': 'name_2', 'stat_2': 12}]
Now I want to add to this list of dictionaries a stat_3 that has the corresponding values for each dictionary item of 100 and 120.现在我想在这个字典列表中添加一个 stat_3,它具有每个字典项 100 和 120 的对应值。
My intended result is:我的预期结果是:
updated_data = [{'stat_1': 'name_1', 'stat_2': 10, 'stat_3': 100}, {'stat_1': 'name_2', 'stat_2': 12, 'stat_3: 120}]
I know you can append to one dictionary item but how would I go about this with two dictionary items in a list?我知道你可以 append 到一个字典项目,但我将如何 go 与列表中的两个字典项目有关? Is a for loop required?
是否需要 for 循环? Appreciate the help!
感谢帮助!
updated_data = data
updated_data[0].update({'stat_3': 100})
updated_data[1].update({'stat_3': 120})
Will sort you, matey.会给你排序的,伙计。
This should work fine:这应该可以正常工作:
data[0]['stat_3'] = 100
data[1]['stat_3'] = 120
if you have a lot of dictionaries in your data
list i would do this:如果您的
data
列表中有很多字典,我会这样做:
for i in range(len(data)):
data[i]['stat_3'] = value #(whatever value you want)
Here's a one-liner:这是一个单行:
data = [{'1': 1, '2': 2}, {'11': 11, '22': 22}]
append = {'C': 'c', 'D': 'd', 'E': 'e'}
[d.update(append) for d in data]
print(data)
As a side-effect, this creates a list
full of None
as long as len(data)
.作为副作用,只要
len(data)
,这将创建一个完整的list
None
。 However, no reference to it is saved, so it should be garbage collected immediately.但是,没有保存对它的引用,因此应该立即对它进行垃圾回收。
Output: Output:
[{'1': 1, '2': 2, 'C': 'c', 'D': 'd', 'E': 'e'},
{'11': 11, '22': 22, 'C': 'c', 'D': 'd', 'E': 'e'}]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.