简体   繁体   中英

Python - Create list of dictionaries from multiple lists of values

I have multiple lists of data, for example: age, name, gender, etc. All of them in order, meaning that the x record of every list belongs to the same person.

What I'm trying to create is a list of dictionaries from these lists in the best pythonic way. I was able to create it using one of the lists, but not sure how to scale it from there.

What I currently have:

ages = [20, 21, 30]
names = ["Jhon", "Daniel", "Rob"]
list_of_dicts = [{"age": value} for value in ages]

It returns:

[{'age': 20}, {'age': 21}, {'age': 30}]

What I want:

[{'age': 20, 'name': 'Jhon'}, {'age': 21, 'name': 'Daniel'}, {'age': 30, 'name': 'Rob'}]

You need to zip :

ages = [20, 21, 30]
names = ["Jhon", "Daniel", "Rob"]
list_of_dicts = [{"age": value, 'name': name}
                 for value, name in zip(ages, names)]

You can take this one step further and use a double zip (useful if you have many more keys):

keys = ['ages', 'names']
lists = [ages, names]
list_of_dicts = [dict(zip(keys, x)) for x in zip(*lists)]

output:

[{'age': 20, 'name': 'Jhon'},
 {'age': 21, 'name': 'Daniel'},
 {'age': 30, 'name': 'Rob'}]

Less obvious code than @mozway's, but has imho one advantage - it relies only on a single definition of a mapping dictionary so if you need to add/remove keys you have to change only one k:v pair.

ages = [20, 21, 30]
names = ["Jhon", "Daniel", "Rob"]

d = {
        "name" : names,
        "age" : ages
    }

list_of_dicts = [dict(zip(d,t)) for t in zip(*d.values())]

print(list_of_dicts)

For Fun:) You can use functools.reduce :

>>> from functools import reduce
>>> reduce (lambda l,t: l+[{'name':t[0] , 'age':t[1]}], zip(ages, names), [])
[{'name': 20, 'age': 'Jhon'},
 {'name': 21, 'age': 'Daniel'},
 {'name': 30, 'age': 'Rob'}]

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