在Python中,可以通过以下步骤在列表的嵌套字典中按键添加列中的值:
data = [
{"name": "Alice", "age": 25, "city": "New York"},
{"name": "Bob", "age": 30, "city": "San Francisco"},
{"name": "Charlie", "age": 35, "city": "Seattle"}
]
salary_values = [5000, 6000, 7000]
update()
方法来实现:for i in range(len(data)):
data[i].update({"salary": salary_values[i]})
下面是一个完整的示例代码:
data = [
{"name": "Alice", "age": 25, "city": "New York"},
{"name": "Bob", "age": 30, "city": "San Francisco"},
{"name": "Charlie", "age": 35, "city": "Seattle"}
]
salary_values = [5000, 6000, 7000]
for i in range(len(data)):
data[i].update({"salary": salary_values[i]})
print(data)
输出结果为:
[
{"name": "Alice", "age": 25, "city": "New York", "salary": 5000},
{"name": "Bob", "age": 30, "city": "San Francisco", "salary": 6000},
{"name": "Charlie", "age": 35, "city": "Seattle", "salary": 7000}
]
这样,我们就成功地在列表的嵌套字典中按键添加了列中的值。
领取专属 10元无门槛券
手把手带您无忧上云