Reputation: 61
I have a list which contains a dictionary and looks like this:
myList = [{'key-1': 'a', 'key-2': 10},
{'key-1': 'b', 'key-2': 20}]
Now I want to add to each items of the list a new key and value. For this I have a list, which looks like this:
new = [50,100]
How can I add new to myList, that it looks like:
mynewlist = [{'key-1': 'a', 'key-2': 10, 'key-3':50},
{'key-1': 'b', 'key-2': 20, 'key-3':100}]
I am very grateful for any help!
Upvotes: 1
Views: 57
Reputation: 55
myList = [{'key-1': 'a', 'key-2': 10},
{'key-1': 'b', 'key-2': 20}]
new = [50,100]
for i in range(len(myList)):
myList[i]['key-3'] = new[i]
myList
OT:
[{'key-1': 'a', 'key-2': 10, 'key-3': 50},
{'key-1': 'b', 'key-2': 20, 'key-3': 100}]
Upvotes: 2
Reputation: 71689
Let us try with list comprehension
and dict
unpacking if you don't want to modify the existing dictionaries in myList
in-place
[{**d, 'key-3': v} for d, v in zip(myList, new)]
[{'key-1': 'a', 'key-2': 10, 'key-3': 50},
{'key-1': 'b', 'key-2': 20, 'key-3': 100}]
Upvotes: 3
Reputation: 120401
for d, value in zip(myList, new):
d.update({f"key-{len(l)+1}": value})
>>> myList
[{'key-1': 'a', 'key-2': 10, 'key-3': 50},
{'key-1': 'b', 'key-2': 20, 'key-3': 100}]
Upvotes: 1
Reputation: 82765
If you know the key in advance then use dict.update
Ex:
myList = [{'key-1': 'a', 'key-2': 10},
{'key-1': 'b', 'key-2': 20}]
new = [50,100]
new_key = 'key-3'
for d, n in zip(myList, new):
d.update({new_key: n})
print(myList)
Upvotes: 1
Reputation: 11474
As follows:
c = [
{'key-1': 'a', 'key-2': 10},
{'key-1': 'b', 'key-2': 20}]
new_values = [50, 100]
for d, value in zip(c, new_values):
d['key-3'] = value
print(c)
Upvotes: 1