![](/img/trans.png)
[英]How do you split a dictionary string value in a list of dictionaries to add a new dictionary item?
[英]How do you join a list to a dictionary of lists as a new item - python?
也許是一個簡單的問題:
在python中,我有一個字典列表,我想在列表中的每個字典中添加一個列表作為新項?
例如,我有字典列表:
list_dict =[{'id':1, 'text':'John'},
{'id':2, 'text':'Amy'},
{'id':3, 'text':'Ron'}]
並列出:
list_age = [23, 54, 41]
然后,如何添加列表以生成字典列表:
list_dict =[{'id':1, 'text':'John', 'age':23},
{'id':2, 'text':'Amy', 'age':54},
{'id':3, 'text':'Ron', 'age':41}]
我不確定在這里使用正確的代碼嗎?
使用zip
,遍歷匹配對並更新字典:
>>> for d, a in zip(list_dict, list_age):
... d["age"] = a
...
>>> list_dict
[{'id': 1, 'text': 'John', 'age': 23}, {'id': 2, 'text': 'Amy', 'age': 54}, {'id': 3, 'text': 'Ron', 'age': 41}]
如果list_age
和list_dict
的長度相同,請嘗試以下循環:
for i, j in zip(list_dict, list_age):
i['age']=j
輸出 :
[{'id': 1, 'text': 'John', 'age': 23}, {'id': 2, 'text': 'Amy', 'age': 54}, {'id': 3, 'text': 'Ron', 'age': 41}]
這樣的事情可能會起作用
for index, item in enumerate(list_age):
list_dict[index]['age'] = item
編輯:如@Netwave所述,您應確保len(list_age)
不大於len(list_dict)
。
添加列表以產生字典列表:
for a, b in zip(list_dict, list_englishmark):
a["englishmark"] = b
print(list_dict)
輸出:
[{'id':1,'name':'mari','englishmark':80},{'id':2,'name':'Arun','englishmark':54},{'id': 3,'name':'ram','englishmark':75}]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.