Siddhesh Patil
Siddhesh Patil

Reputation: 53

How to return a dictionary based on a certain element in the list?

Given a list of lists that contains a tuple and an integer, how to return a dictionary based on a certain element in the list?

[[('A Sam', 'count1'), 1],
 [('A Sam', 'count2'), 2],
 [('T King', 'count1'), 2],
 [('C Baskin', 'count2'), 1]]

Given this, as input, I need to return a dictionary

{"A Sam": [1,2], "T King": [2,0], "C Baskin": [0,1]}

as the output. For a particular key named "A Sam" the value of the dictionary should be a list of count1 and count2 where count1 and count2 are the 2 elements in the list of lists. How would I go about doing this?

Upvotes: 2

Views: 64

Answers (2)

Mykola Zotko
Mykola Zotko

Reputation: 17854

You can use defaultdict:

from collections import defaultdict

dct = defaultdict(lambda :[0] * 2) # defaultdict that returns [0, 0]

for (name, count), n in lst:
  v = dct[name]
  v[int(count[-1]) - 1] += n # get the last element from 'count' and use it as index

Output:

{'A Sam': [1, 2], 'C Baskin': [0, 1], 'T King': [2, 0]})

Upvotes: 1

Shadowcoder
Shadowcoder

Reputation: 972

It is little bit long but it works.

l=[[('A Sam', 'count1'), 1], [('A Sam', 'count2'), 2], [('T King', 'count1'), 2], [('C Baskin', 'count2'), 1]]
D={}
for j in l:
    if j[0][0] in D:
        if j[0][1]=='count1':
            D[j[0][0]][0]=j[1]
        else:
            D[j[0][0]][1]=j[1]
    else:
        if j[0][1]=='count1':
            D[j[0][0]]=[j[1],0]
        else:
            D[j[0][0]]=[0,j[1]]

Upvotes: 1

Related Questions