userpisquared
userpisquared

Reputation: 79

Create dictionary of dictionaries using list of labels

I'm trying to create a dictionary that labels a given dictionary that I have created. Basically, I have created a list that looks something like,

labels = ["id1", "id2", "id3"] .

I then have a list of dictionaries that look like,

dicts = [{'to': 2, 'give':1}, {'you': 1,'an':1}, {'example' :1}] .

What I'm trying to do is create a new dictionary that correctly labels each dictionary i.e. id1 goes with dictionary1, id2 to dictionary2 etc. Basically make a new dictionary looking like,

new_dict = {"id1" : {'to': 2, 'give':1}, "id2" : {'you': 1,'an':1}, "id3" : {'example' :1}}

I cannot get the notation correct and it's very frustrating. Does anyone have an easy solution?

Upvotes: 1

Views: 1322

Answers (2)

Taimoor Qureshi
Taimoor Qureshi

Reputation: 630

you can do it as

labels = ["id1", "id2", "id3"]
dicts = [{'to': 2, 'give':1}, {'you': 1,'an':1}, {'example' :1}]

new_dict = dict(zip(labels, dicts))
print(new_dict)
//{'id2': {'you': 1, 'an': 1}, 'id3': {'example': 1}, 'id1': {'to': 2, 'give': 1}}

Upvotes: 5

Unmitigated
Unmitigated

Reputation: 89224

You can use a dictionary comprehension with zip:

result = {key: val for key, val in zip(labels, dicts)}

Demo

Upvotes: 2

Related Questions