Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python access dictionary inside list of a dictionary

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
like image 845
MBasith Avatar asked Aug 09 '17 13:08

MBasith


People also ask

Can you have a dictionary inside a list Python?

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.


2 Answers

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.

like image 72
Laszlowaty Avatar answered Oct 19 '22 04:10

Laszlowaty


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'])
like image 30
aristotll Avatar answered Oct 19 '22 05:10

aristotll