Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge two lists,one as keys, one as values, into a dict in Python [duplicate]

Is there any build-in function in Python that merges two lists into a dict? Like:

combined_dict = {}

keys = ["key1","key2","key3"] 

values = ["val1","val2","val3"]

for k,v in zip(keys,values):
    combined_dict[k] = v

Where:

keys acts as the list that contains the keys.

values acts as the list that contains the values

There is a function called array_combine that achieves this effect.

like image 572
xiaohan2012 Avatar asked May 24 '12 03:05

xiaohan2012


People also ask

How do I merge multiple dictionaries values having the same key in python?

The simplest way to merge two dictionaries in python is by using the unpack operator(**). By applying the "**" operator to the dictionary, it expands its content being the collection of key-value pairs.

Can keys be duplicate in dictionary python?

Dictionaries in Python First, a given key can appear in a dictionary only once. Duplicate keys are not allowed.

Can we repeat the values of Key in dictionary?

If you want to keep duplicate keys in a dictionary, you have two or more different values that you want to associate with same key in dictionary. The dictionary can not have the same keys, but we can achieve a similar effect by keeping multiple values for a key in the dictionary.


1 Answers

Seems like this should work, though I guess it's not one single function:

dict(zip(["key1","key2","key3"], ["val1","val2","val3"]))

from here: How do I combine two lists into a dictionary in Python?

like image 111
TankorSmash Avatar answered Oct 02 '22 20:10

TankorSmash