a_wise
a_wise

Reputation: 71

Clean way to combine list of lists into a dictionary?

I have two lists:

ind_vars_unique_list = [['R1'], ['Samoan', 'English'], ['Rural', 'Urban']]
ind_vars = ['Round', 'PrefLang', 'Rural']

I want to create a dictionary that looks like:

{'R1': 'Round', 'Samoan':'PrefLang', 'English':'PrefLang', 'Rural':'Rural', 'Urban':'Rural'}

I can get a solution using a dictionary comprehension approach:

{ind_vars_unique_list[i][j]:ind_vars[i] for i in range(len(ind_vars)) for j in range(len(ind_vars_unique_list[i]))}

But I am wondering if there is a cleaner or more pythonic way of doing this, maybe with dict and zip?

Upvotes: 3

Views: 58

Answers (1)

ggorlen
ggorlen

Reputation: 56975

Correct, zip is the way to go:

>>> {x: v for k, v in zip(ind_vars_unique_list, ind_vars) for x in k}
{'R1': 'Round', 'Samoan': 'PrefLang', 'English': 'PrefLang', 'Rural': 'Rural', 'Urban': 'Rural'}

Upvotes: 3

Related Questions