简体   繁体   中英

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.

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']}

字典没有排序,因此您需要对字典键进行排序,以确保它们与列表中所需的索引对齐。

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

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']}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM