nephos
nephos

Reputation: 123

How do I add keys to a dictionary in a list of dictionaries?

Simple question that I can't seem to find an answer to:

How do I add/append a key to a dictionary that resides in a list of dictionaries?


Given the list below:

list = [{'key-1': 'value-1', 'key-2': 'value-2'}, {'key-A': 'value-A'}]

I want to add 'key-B": "value-B' in the second dictionary for the result to be:

list = [{'key-1': 'value-1', 'key-2': 'value-2'}, 
        {'key-A': 'value-A', 'key-B': 'value-B'}]

I thought I could just .update or .append to it but, no such luck.

Any assistance with this is greatly appreciated.

Upvotes: 5

Views: 7227

Answers (2)

DevC
DevC

Reputation: 7423

Dictionary don't have any append method, For example if you have a dictionary as

dict = {'First':1, 'Second':2}, 

then you can add a third item as

dict['Third']=3. 

Similarly in your case you want to change the second element of your list so list[1] will represent your second element and this element is dictionary so you can operate in the same way as dictionary

list[1]['key-B'] = 'value-B'

Your list has two elements and in this case both are dictionaries. Dictionary do have a update method and if you want to use update of dictionary then first access the dictionary element of your list and then update

list[1].update({'key-C':'value-C'})

You can check what methods are available using dir(list[1]) in your python interactive shell

Upvotes: 2

edi_allen
edi_allen

Reputation: 1872

just do this.

list[1]['key-B'] = 'value-B'

OUTPUT

print(list)
[{'key-2': 'value-2', 'key-1': 'value-1'}, {'key-B': 'value-B', 'key-A': 'value-A'}] 

Upvotes: 4

Related Questions