Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: how to build a dict from plain list of keys and values

I have a list of values like:

["a", 1, "b", 2, "c", 3]

and I would like to build such a dict from it:

{"a": 1, "b": 2, "c": 3}

What is the natural way to do it in Python?

like image 353
lithuak Avatar asked Feb 28 '12 16:02

lithuak


People also ask

How can I make a dictionary from separate lists of keys and values?

For this, simply declare a dictionary, and then run nested loop for both the lists and assign key and value pairs from list values to dictionary.

How do you create a dictionary using keys and values?

To create a Python dictionary, we pass a sequence of items (entries) inside curly braces {} and separate them using a comma ( , ). Each entry consists of a key and a value, also known as a key-value pair. Note: The values can belong to any data type and they can repeat, but the keys must remain unique.

Can you create a dictionary from a list in Python?

You can convert a Python list to a dictionary using the dict. fromkeys() method, a dictionary comprehension, or the zip() method. The zip() method is useful if you want to merge two lists into a dictionary.

How do you create a dictionary with one key and multiple values?

In python, if we want a dictionary in which one key has multiple values, then we need to associate an object with each key as value. This value object should be capable of having various values inside it. We can either use a tuple or a list as a value in the dictionary to associate multiple values with a key.


1 Answers

>>> x = ["a", 1, "b", 2, "c", 3]
>>> i = iter(x)
>>> dict(zip(i, i))
{'a': 1, 'c': 3, 'b': 2}
like image 195
Josh Lee Avatar answered Oct 17 '22 19:10

Josh Lee