arti13
arti13

Reputation: 43

How to create a list of dictionary object from two lists?

I have two lists:

list_of_ids = [46571928, 675829237, 9674826585, 172395729]
list_of_positions = [1, 4, 9, 13]

I want to create the following list of dictionaries from the two lists:

list_of_dict = [{'id': 46571928, 'position': 1}, {'id': 675829237, 'position': 4}, {'id': 9674826585, 'position': 9}, {'id': 172395729, 'position': 13}]

I have tried creating two dictionaries and then merging them together, but it only maps the first values.

ids = ['id']
position = ['position']

dict_id = dict(zip(ids, list_of_id))
dict_position = dict(zip(position, list_of_positions))

def merge(dict1,dict2):
    res = {**dict1, **dict2}
    return res

list_of_dict = merge(dict_id,dict_position)

So the output is:

[{'id':46571928, 'position': 1}]

I have tried few other things, but it is as close as I got. Can someone help me to figure this out please? Thanks!

Upvotes: 1

Views: 64

Answers (2)

Derek Eden
Derek Eden

Reputation: 4638

[{'id':ID,'position':POS} for ID,POS in zip(list_of_ids,list_of_positions)]

output:

[{'position': 1, 'id': 46571928}, {'position': 4, 'id': 675829237}, {'position': 9, 'id': 9674826585}, {'position': 13, 'id': 172395729}]

Upvotes: 4

ComplicatedPhenomenon
ComplicatedPhenomenon

Reputation: 4199

[{'id': a, 'position': b} for a, b in zip(list_of_ids, list_of_positions)]

Upvotes: 2

Related Questions