Tranquil Oshan
Tranquil Oshan

Reputation: 308

Get keys and values from dictionaries in a list

I have a datastructure like this:

d={0:[{'key':'apple', 'count':50},{'key':'ibm', 'count':25}], 
1: [{'key':'apple', 'count':40},{'key':'ibm', 'count':29}],
2:[{'key':'apple', 'count':44},{'key':'ibm', 'count':21}]}

What I want to accomplish is get a list of the values for each of the tuples in the list. What I am trying to do is:

zipped={}
count=0
for item in d:
    #print(item)
    for i in d[item]:
        zipped[count]=i['count']
        count+=1

The result I get is:

{0: 50, 1: 25, 2: 40, 3: 29, 4: 44, 5: 21}

What I want is something like:

{0:[50,25], 1:[40,29], 2:[44,21]}

How can I get that

Upvotes: 0

Views: 66

Answers (2)

Sagar Lakhani
Sagar Lakhani

Reputation: 11

res = { key:[value["count"] for value in values] for key,values in d.items()}

use this for your required result

Upvotes: 1

Vsevolod Timchenko
Vsevolod Timchenko

Reputation: 756

Yeah, you go too deep. I think you can get away with multiple list comprehension. It should work even if you have an undetermined number of internal values:

zipped = {key: [elem['count'] for elem in internal_list] for key, internal_list in d.items()}

Upvotes: 0

Related Questions