I have a Python Dictionary like:
Mydict = {‘a’: {‘y’: 1, ‘x’: 5}, ‘b’: {‘y’: 10, ‘x’: 8}}
Is there any quick way to access the values corresponding to the key: ‘x’, which in this case is a second level key, regardless of the first level key?
I know it can be done using a for loop like:
mylist=[]
for k in Mydict.keys():
mylist.append(Mydict[k]['x'])
But is there any quick one line method for it?
Using list-comprehension:
Since you do not need the outer keys, you just iterate over the inner dicts, and get the desired
'x'value.Note: This will only work if each inner dict has an
'x'key, to be sure, and to minimize errors, you can do this:This will function the same, only if there is no
'x'key in the dictionary, it will returnNoneinstead of aKeyErrorexception.For timing, and to see which method is best, look at the answer by Thorsten Kranz