Skip to content
Advertisement

How do I convert dict of dicts/nested dicts into dict of list

Heres the original dict

uid_coins = {'141632864': {'username': 'Guest130679138', 'coins': 0}, 
        '141632884': {'username': 'Guest130679156', 'coins': 39123441}, 
        '141632886': {'username': 'Guest130679158', 'coins': 44006638}}

What I am trying to get

d = {'uid':[141632864, 141632884, 141632886], 
'username': ['Guest130679138', 'Guest130679156', 'Guest130679158'], 
'coins': [0, 39123441, 44006638]}

The keys in original dict represent uid.

This is my what I have done:

uid = list(uid_coins.keys())
username = [u_data['username'] for u_data in uid_coins.values()]
coins = [[u_data['coins'] for u_data in uid_coins.values()]]

d = {"uid":uid, "username":username, "coins":coins}


dict((key,d[key]) for d in data for key in d)

But I am rather looking for a generalized approach, to achieve without manually declaring the keys again, just so it should work with new keys in the original data.

Advertisement

Answer

Generalized (based on original version by Andrej Kesely):

d = {}
for k, v in uid_coins.items():
    d.setdefault('uid', []).append(k)
    for i in v.keys():
        d.setdefault(i, []).append(v[i])
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement