Insert dictionary to list of dictionary python
Question:
How can I insert a dictionary to list of dictionary?
newDict = [{'id': 1}, {'id': 2}]
myData = [{'title': 'Bar', 'barname': 'Archer}, {'title': 'Bar', 'barname': 'Archer}]
output:
[{'id': 1, 'title': 'Bar', 'barname': 'Archer}, {'id': 2, 'title': 'Bar', 'barname': 'Archer'}]
Answers:
You can use zip
and dictionary unpacking:
[{**dict_1, **dict_2} for dict_1, dict_2 in zip(newDict, myData)]
[{'id': 1, 'title': 'Bar', 'barname': 'Archer'},
{'id': 2, 'title': 'Bar', 'barname': 'Archer'}]
(or dict_1 | dict_2
starting from Python 3.9)
In case the ids in newDict
are meant to index the elements of myData
(1-based):
[{**id_select, **myData[id_select["id"] - 1]} for id_select in newDict]
Using loops you can do it this way:
for n in range(min(len(newDict),len(myData))):
new,my=newDict[n],myData[n]
for key in my:
new[key] = my[key]
After this your desired output==newDict. You should also think of how you want to deal with duplicate keys if that’s a possibility.
How can I insert a dictionary to list of dictionary?
newDict = [{'id': 1}, {'id': 2}]
myData = [{'title': 'Bar', 'barname': 'Archer}, {'title': 'Bar', 'barname': 'Archer}]
output:
[{'id': 1, 'title': 'Bar', 'barname': 'Archer}, {'id': 2, 'title': 'Bar', 'barname': 'Archer'}]
You can use zip
and dictionary unpacking:
[{**dict_1, **dict_2} for dict_1, dict_2 in zip(newDict, myData)]
[{'id': 1, 'title': 'Bar', 'barname': 'Archer'},
{'id': 2, 'title': 'Bar', 'barname': 'Archer'}]
(or dict_1 | dict_2
starting from Python 3.9)
In case the ids in newDict
are meant to index the elements of myData
(1-based):
[{**id_select, **myData[id_select["id"] - 1]} for id_select in newDict]
Using loops you can do it this way:
for n in range(min(len(newDict),len(myData))):
new,my=newDict[n],myData[n]
for key in my:
new[key] = my[key]
After this your desired output==newDict. You should also think of how you want to deal with duplicate keys if that’s a possibility.