I made a nested dictionary
d = {
'first':{
'key': 'A',
'val': 1
},
'second':{
'key': 'A',
'val': 2
},
'third':{
'key': 'B',
'val': 5
},
'fourth':{
'key': 'B',
'val': 7
}
}
Now suppose I wanted to create a list of values of the nested dictionaries with key being 'key'. What I mean by that is, I want a list of such manner:
L = ['A', 'A', 'B', 'B']
I managed to do it with the help of for loops and value() in this manner:
List = d.values()
L = []
for K in List:
L.append(K['key'])
print(L)
Output:
['A', 'A', 'B', 'B']
but is there something cleaner out there?
You can just use a list comprehension
print([v['key'] for v in d.values()])
you can write like :
keys_list = [record['key'] for record in d.values()]
it will get the values that you mentioned in the output.
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