Convert list to dict Python

Thats a very common question and the answer is: It depends.
It depends on the data in the list and how you want it to be represented in the dictionary.

In this article we go over six different ways of converting a list to a dictionary. You can also watch my advanced one-liner video where we show you some of the content in this article:

1. Convert List of Primitive Data Types to Dict Using Indices as Keys

Problem: Convert a list of primitive data types to a dictionary using the elements indices.

Example: As an example, take this list:

snakes = ['Anaconda', 'Python', 'Cobra', 'Boa', 'Lora' ]


You want to convert this list into a dictionary where each entry consists of a key and a value.

  • The key is each elements index in the list snake.
  • The value is a string element from the list.

So in the end the dictionary should look like this:

d = {0: 'Anaconda', 1: 'Python', 2: 'Cobra', 3: 'Bora', 4: 'Lora'}

Solution Idea: Take a dictionary comprehension and use the enumerate function to generate key-value pairs.

Now lets see, how can you implement the logic to achieve this?

  • First, create an empty dictionary.
  • Second, loop over the list snakes and add the key-value entries to the empty dictionary.
  • To generate the key-value pairs, use Pythons built-in function enumerate[]. This function takes an iterable and returns a tuple for each element in the iterable. In these tuples, the first entry is the elements index and the second entry is the element itself. For example: enumerate['abc'] will give you an enumerate object containing the values [0, 'a'], [1, 'b'], [2, 'c'].

Code: And here is the code.

# list to convert snakes = ['Anaconda', 'Python', 'Cobra', 'Boa', 'Lora' ] # Short hand constructor of the dict class d = {} for index, value in enumerate[snakes]: d[index] = value

And thats all you need, the dictionary d contains just the entries you wanted to have.

A more pythonic way to solve the problem is using a dictionary comprehension. This makes the code shorter and in my opinion even simpler to read. Look at this:

# list to convert snakes = ['Anaconda', 'Python', 'Cobra', 'Boa', 'Lora' ] # dictionary comprehension d = {index: value for index, value in enumerate[snakes]}

Try It Yourself:

So once again, Pythons built-in function enumerate cracks the problem, the rest is simple.

2. Convert List of Key-Value Tuples to Dict

Problem: How to convert a list of tuples into a dictionary in Python using the first tuple values as dictionary keys and the second tuple values as dictionary values.

Example: We take a list of snake color tuples as example.

snake_colors = [['Anaconda', 'green'], ['Python', 'green'], ['Cobra', 'red'], ['Boa', 'light-green'], ['Lora', 'green-brown']]

Solution: Actually, this problem is even easier to solve as the first one because the work of the function enumerate is already done, all we need to do is add the entries to the dictionary.

Such a list can be mapped to a dictionary simply by calling the dict[] constructor with this list as argument. So the whole code would be as simple as this:

d = dict[snake_colors]

3. Convert Two Lists to Single Dict

First, lets define your problem more precisely. You have two lists of elements. The first list contains our keys and the second one contains the values. In the end, you want to have a dictionary whose entries should look like this:

key = lst1[i], value = lst2[i]

Again, Python brings all the functions you need as built-in functions. Suppose that your lists look like this:

snakes = ['Anaconda', 'Python', 'Cobra', 'Boa', 'Lora'] colors = ['green', 'green', 'red', 'light-green', 'green-brown']

To transform these two lists into the same dictionary as in the previous paragraph we need the built-in function zip[]. It takes two or more iterables as arguments and creates tuples from them.

The tuples look like this: [iterable1[i], iterable2[i], , iterableN[i]]

With the following line of code we would get a list of key-value tuples:

snakes = ['Anaconda', 'Python', 'Cobra', 'Boa', 'Lora'] colors = ['green', 'green', 'red', 'light-green', 'green-brown'] tuples = list[zip[snakes, colors]]

We already saw in section 2 how we can convert a list of tuples to a dictionary. Now, Python is very powerful and doesnt require the conversion to a list before we can transform the list of tuples to a dictionary, instead we can pass the result of zip[snakes, colors] directly to the dict constructor.

The final code looks like this:

snakes = ['Anaconda', 'Python', 'Cobra', 'Boa', 'Lora'] colors = ['green', 'green', 'red', 'light-green', 'green-brown'] d = dict[zip[snakes, colors]]

4. Convert a List of Alternating Key, Value Entries to a Dict

Idea: Use slicing to get two separate lists, one with the keys, one with the values. Zip them together and create the dictionary by passing the zip result to the dict[] constructor.

To make it more visual lets take as an example the following list of city names and zip codes [no more snakes;]]:

city_zip = ['Berlin', 10178, 'Stuttgart', 70591, 'München', 80331, 'Hamburg', 20251]

From this list we want to create a dictionary where the city names are the keys and their zip codes are the values.

There are many different solution to this problem, therefore I decided to show you a solution that I consider really pythonic. It uses slicing and combines it with what we saw in the previous section.

As you know [if not refresh it here] we can set a start value, an end value and a step value for slicing. So with city_zip[::2] we get all the city names and with city_zip[1::2] we get the zip codes. Putting it all together we get this code:

city_zip = ['Berlin', 10178, 'Stuttgart', 70591, 'München', 80331, 'Hamburg', 20251] city = city_zip[::2] zip_code = city_zip[1::2] d = dict[zip[city, zip_code]]

5. Convert a List of Dictionaries to a Single Dict

Idea: Use a dictionary unpacking in a loop. The method update[] of the dict class adds the data to an existing dictionary.

Lets imagine the following use case: A vehicle sends a constant stream of telemetry data as dictionaries. To reduce latency the dictionaries contain only the updates. To get the latest overall state of the vehicle we want to merge all those dictionaries into one. As you might have guessed, once again, Python makes it very easy. Here is the code:

state_0 = {'coord_x': 5.123, 'coord_y': 4.012, 'speed': 0, 'fuel': 0.99} state_1 = {'coord_x': 5.573, 'speed': 10, 'fuel': 0.83} state_2 = {'coord_x': 6.923, 'speed': 25, 'fuel': 0.75} state_3 = {'coord_x': 7.853, 'coord_y': 4.553, 'fuel': 0.68} state_4 = {'coord_x': 10.23, 'speed': 50, 'fuel': 0.61} d = dict[state_0] data_stream = [state_0, state_1, state_2, state_3, state_4] for state in data_stream: # updates only the changed entries in the dict d.update[**state]

After processing the data stream our dictionary d contains the current state of the vehicle.

6. Convert a List to Dictionary Keys in Python

Idea: Initialize the dictionary with the dict constructor. As the argument pass in the result of zipping together the list of keys with a generator which returns constantly a default value.

I would like to rephrase the problem into a practical problem first. We have a list of names, say players, and want to create a dictionary where we can comfortably update their points for the current game.

With Pythons built-in function zip we can zip together two lists and pass the result of zip to the dict constructor. Since we only have one list of keys we need to create a list of default values of the same length somehow. I chose a generator expression to do this. It returns the default value 0 for each element in the players list. Now we can throw the players list and the generator expression in the zip function and pass the result to the dict constructor thats all!

players = ['Alice', 'Bob', 'Cloe', 'Dain'] default_value_gen = [0 for x in range[len[players]]] d = dict[zip[players, default_value_gen]]

Conclusion

As we have seen in this article, Python has powerful built-in functions that make it really easy to convert data from any given format to a dictionary. To prepare yourself for a new to-dictionary-transformation challenge I recommend you to read our article about dictionaries.

Knowing dictionaries and their methods well is the base for leveraging their power under any circumstances.

Where to Go From Here?

Want to start earning a full-time income with Pythonwhile working only part-time hours? Then join our free Python Freelancer Webinar.

It shows you exactly how you can grow your business and Python skills to a point where you can work comfortable for 3-4 hours from home and enjoy the rest of the day [=20 hours] spending time with the persons you love doing things you enjoy to do.

Become a Python freelancer now!

Video liên quan

Chủ Đề