Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a better way to create a list of values of a nested dictionary?

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?

like image 985
Zee Avatar asked Oct 21 '25 06:10

Zee


2 Answers

You can just use a list comprehension

print([v['key'] for v in d.values()])
like image 99
2 revs, 2 users 80%Sayse Avatar answered Oct 23 '25 21:10

2 revs, 2 users 80%Sayse


you can write like :

keys_list = [record['key'] for record in d.values()]

it will get the values that you mentioned in the output.

like image 21
Sayed A. Omar Avatar answered Oct 23 '25 20:10

Sayed A. Omar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!