Rasv
Rasv

Reputation: 13

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

Upvotes: 1

Views: 462

Answers (2)

matszwecja
matszwecja

Reputation: 7971

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)

Upvotes: 1

mozway
mozway

Reputation: 260455

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

Upvotes: 3

Related Questions