Servin Vashnar
Servin Vashnar

Reputation: 11

How to convert dict of dict to dict of list

I've got a nested dictionary like this:

{'name': {0: 'name1', 1: 'name2'}, 'age': {0: 'age1', 1: 'age2'}}

And I want to convert it to this:

{'name': [name2, name1], 'age': [age2, age1]}

I'm unsure of how to extract the values form the inner dictionaries, as well as sort them in the sense that if I were to sort the ages, the names would also be sorted in the same fashion. Any help is appreciated.

Upvotes: 0

Views: 69

Answers (3)

Dom Weldon
Dom Weldon

Reputation: 1738

Dictionaries are not ordered so you will need to sort the dictionary keys to ensure they align with the indices you want in your list.

d = {k: [v[i] for i in sorted(v.keys(), reverse=True)] for k, v in data.items()}

Upvotes: 1

jpp
jpp

Reputation: 164633

This is one functional way:

from operator import itemgetter

data = {'name': {0: 'name1', 1: 'name2'}, 'age': {0: 'age1', 1: 'age2'}}

d = {k: list(map(itemgetter(1), sorted(v.items()))) for k, v in data.items()}

# {'age': ['age1', 'age2'], 'name': ['name1', 'name2']}

Upvotes: 1

sacuL
sacuL

Reputation: 51335

You can try dictionary comprehension, if your dictionary is called d:

# Python 2:
{k:d[k].values() for k in d}
# Python 3:
{k:list(d[k].values()) for k in d}

Which returns:

{'age': ['age1', 'age2'], 'name': ['name1', 'name2']}

Upvotes: 2

Related Questions