Lina
Lina

Reputation: 61

How do I add values to dictionaries which is in a list?

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

Answers (5)

AdrianSK
AdrianSK

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

Shubham Sharma
Shubham Sharma

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

Corralien
Corralien

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

Rakesh
Rakesh

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

0 _
0 _

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

Related Questions