Jonathan Brodie
Jonathan Brodie

Reputation: 3

How do I add a new key value pair to a list of dictionaries?

Hi new python coder here, let's say I have a list of dictionaries:

data = [{'stat_1': 'name_1', 'stat_2': 10}, {'stat_1': 'name_2', 'stat_2': 12}]

Now I want to add to this list of dictionaries a stat_3 that has the corresponding values for each dictionary item of 100 and 120.

My intended result is:

updated_data = [{'stat_1': 'name_1', 'stat_2': 10, 'stat_3': 100}, {'stat_1': 'name_2', 'stat_2': 12, 'stat_3: 120}]

I know you can append to one dictionary item but how would I go about this with two dictionary items in a list? Is a for loop required? Appreciate the help!

Upvotes: 0

Views: 745

Answers (3)

Razzle Shazl
Razzle Shazl

Reputation: 1330

Here's a one-liner:

data = [{'1': 1, '2': 2}, {'11': 11, '22': 22}]
append = {'C': 'c', 'D': 'd', 'E': 'e'}

[d.update(append) for d in data]

print(data)

As a side-effect, this creates a list full of None as long as len(data). However, no reference to it is saved, so it should be garbage collected immediately.

Output:

[{'1': 1, '2': 2, 'C': 'c', 'D': 'd', 'E': 'e'},
{'11': 11, '22': 22, 'C': 'c', 'D': 'd', 'E': 'e'}]

Upvotes: 0

Constantine Westerink
Constantine Westerink

Reputation: 321

This should work fine:

data[0]['stat_3'] = 100
data[1]['stat_3'] = 120

if you have a lot of dictionaries in your data list i would do this:

for i in range(len(data)):
   data[i]['stat_3'] = value #(whatever value you want)   

Upvotes: 1

hd1
hd1

Reputation: 34677

updated_data = data

updated_data[0].update({'stat_3': 100})

updated_data[1].update({'stat_3': 120})

Will sort you, matey.

Upvotes: 1

Related Questions