Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 222
nephos Avatar asked Sep 23 '13 17:09

nephos


People also ask

How do you get the keys of a dictionary in a list?

Method 1: Get dictionary keys as a list using dict. The dict. keys() method in Python Dictionary, returns a view object that displays a list of all the keys in the dictionary in order of insertion.

Can you nest a dictionary in a list?

You can have dicts inside of a list. The only catch is that dictionary keys have to be immutable, so you can't have dicts or lists as keys.

Can list be used as keys in a dictionary in Python?

We can use integer, string, tuples as dictionary keys but cannot use list as a key of it .


1 Answers

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'}] 
like image 73
edi_allen Avatar answered Sep 19 '22 15:09

edi_allen