asd
asd

Reputation: 183

Read Multiple Dictionaries into a nested list

I am reading below list into a Counter and I want to group all keys into a nested list as shown below

import collections
A=["cool","lock","cook"]
B=[]
d={}
for i in A:
    B.append(collections.Counter(i))
print(B)

## B value is [Counter({'o': 2, 'c': 1, 'l': 1}), Counter({'l': 1, 'o': 1, 'c': 1, 'k': 1}), Counter({'o': 2, 'c': 1, 'k': 1})]
for i in B:
    for j in i.keys():
         d.setdefault( d[j],[]).append(i.values())
print(d)

I am getting a Key Error, I have used Setdefault() but able to get it work.

Needed output:

{'o':[2,1,2],'c':[1,1,1],'l':[1,1],'k':[1,1] }

Upvotes: 1

Views: 54

Answers (1)

Red
Red

Reputation: 27557

Here is how:

import collections

A = ["cool", "lock", "cook"]
B = []
d = {}
for i in A:
    B.append(collections.Counter(i))
    
for i in B:
    for j in i:
        if j in d:
            d[j].append(i[j])
        else:
            d[j] = [i[j]]
print(d)

Output:

{'c': [1, 1, 1], 'o': [2, 1, 2], 'l': [1, 1], 'k': [1, 1]}

You may even use map when defining B to improve the efficiency:

import collections

A = ["cool", "lock", "cook"]
B = map(collections.Counter, A)
d = {}

for i in B:
    for j in i:
        if j in d:
            d[j].append(i[j])
        else:
            d[j] = [i[j]]
print(d)

Upvotes: 1

Related Questions