8-Bit Borges
8-Bit Borges

Reputation: 10033

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?

Upvotes: 2

Views: 2280

Answers (2)

Arun V Jose
Arun V Jose

Reputation: 3379

Counter is a good option. But according to this question we can use more simple option. Check this out.

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

res = {}
for user in users.items():          # return each key:value pair as tuple
    res[user[0]] = {}               # first element of tuple used as key in `res` for each list
    for tag in user[1]:             # return each element of list 
        res[user[0]][tag] = 1       # assign value as 1 of each element.

print res

Output:

{'u1': {'alternative': 1, 'pop': 1, 'rock': 1}, 'u2': {'indie': 1, 'chamber pop': 1, 'rock': 1}}

Upvotes: 1

niemmi
niemmi

Reputation: 17263

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.

Upvotes: 1

Related Questions