Hi I have the below dictionary which has a value with a list, and inside the list is a dictionary. Is there a way to call the dictionary value inside the list using the key instead of the list index? The dictionary inside the list may vary so the index value may not always provide the right key value pair. But if I am able to use the key I can always get the correct value.
mylist = {'mydict': [{'A': 'Letter A'}, {'B': 'Letter C'}, {'C': 'Letter C'}]}
print(mylist['mydict'][0]['A'])
Current Output:
Letter A
Desired Query:
print(mylist['mydict']['A'])
Letter A
In Python, you can have a List of Dictionaries. You already know that elements of the Python List could be objects of any type. In this tutorial, we will learn how to create a list of dictionaries, how to access them, how to append a dictionary to list and how to modify them.
Take a look at the code below:
mylist = {'mydict': [{'A': 'Letter A'}, {'B': 'Letter C'}, {'C': 'Letter C'}]}
for dictionary in mylist['mydict']:
try:
print(dictionary['A'])
except KeyError:
pass
'Letter A'
You iterate over a dictionaries inside your list, and then try to call your A
key. You catch KeyError
because in the dictionary key may be absent.
Try the following code to generate the new dict.
mylist = {'mydict': [{'A': 'Letter A'}, {'B': 'Letter C'}, {'C': 'Letter C'}]}
newDict={}
for item in mylist['mydict']:
newDict.update(item)
mylist['mydict']=newDict
print(mylist['mydict']['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