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.
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.
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.
We can use integer, string, tuples as dictionary keys but cannot use list as a key of it .
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'}]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With