data_garden data_garden - 15 days ago 4
Python Question

Python - populate nested dictionaries

Starting form a list:

user1 = ['alternative', 'rock', 'pop']


I can populate a
dictionary
with the number of appearences of each item.

u1={}
for tag in user1:
u1[tag]=1
print u1


and get:
{'alternative': 1, 'pop': 1, 'rock': 1}


likewise, for:

user2 = ['indie', 'rock', 'chamber pop']


the same:

u2={}
for tag in user2:
u2[tag]=1
print u2


and get:
{'indie': 1, 'chamber pop': 1, 'rock': 1}
, and so on.

but lets say I want to populate this
dict
in the same fashion:

users = {
u1:{},
u2:{},
u3:{},
...
...
}


how can I do it?

Answer

Let's say you have users and lists already stored to a dictionary. Then you could iterate over all key value pairs within dictionary comprehension and use Counter to convert the list to dict with counts:

from collections import Counter

users = {
    'u1': ['alternative', 'rock', 'pop'],
    'u2': ['indie', 'rock', 'chamber pop'],
    'u3': ['indie', 'rock', 'alternative', 'rock']
}

res = {k: Counter(v) for k, v in users.items()}
print(res)

Output:

{'u1': Counter({'alternative': 1, 'pop': 1, 'rock': 1}), 
 'u3': Counter({'rock': 2, 'indie': 1, 'alternative': 1}), 
 'u2': Counter({'indie': 1, 'chamber pop': 1, 'rock': 1})}

To break above a bit users.items() returns an iterable of (key, value) tuples:

>>> list(users.items())
[('u2', ['indie', 'rock', 'chamber pop']), ('u1', ['alternative', 'rock', 'pop']), ('u3', ['indie', 'rock', 'alternative', 'rock'])]

Then dict comprehension turns the list to dict containing the counts:

>>> Counter(['indie', 'rock', 'chamber pop'])
Counter({'rock': 1, 'indie': 1, 'chamber pop': 1})

Finally for each the user name and resulting Counter are added the to the result dict.