Convert list to dict in python

If you are still thinking what the! You would not be alone, its actually not that complicated really, let me explain.

We want to turn the following list into a dictionary using the odd entries (counting from 1) as keys mapped to their consecutive even entries.

l = ["a", "b", "c", "d", "e"]

dict()

To create a dictionary we can use the built in dict function for Mapping Types as per the manual the following methods are supported.

dict(one=1, two=2) dict({'one': 1, 'two': 2}) dict(zip(('one', 'two'), (1, 2))) dict([['two', 2], ['one', 1]])

The last option suggests that we supply a list of lists with 2 values or (key, value) tuples, so we want to turn our sequential list into:

l = [["a", "b"], ["c", "d"], ["e",]]

We are also introduced to the zip function, one of the built-in functions which the manual explains:

returns a list of tuples, where the i-th tuple contains the i-th element from each of the arguments

In other words if we can turn our list into two lists a, c, e and b, d then zip will do the rest.

slice notation

Slicings which we see used with Strings and also further on in the List section which mainly uses the range or short slice notation but this is what the long slice notation looks like and what we can accomplish with step:

>>> l[::2] ['a', 'c', 'e'] >>> l[1::2] ['b', 'd'] >>> zip(['a', 'c', 'e'], ['b', 'd']) [('a', 'b'), ('c', 'd')] >>> dict(zip(l[::2], l[1::2])) {'a': 'b', 'c': 'd'}

Even though this is the simplest way to understand the mechanics involved there is a downside because slices are new list objects each time, as can be seen with this cloning example:

>>> a = [1, 2, 3] >>> b = a >>> b [1, 2, 3] >>> b is a True >>> b = a[:] >>> b [1, 2, 3] >>> b is a False

Even though b looks like a they are two separate objects now and this is why we prefer to use the grouper recipe instead.

grouper recipe

Although the grouper is explained as part of the itertools module it works perfectly fine with the basic functions too.

Some serious voodoo right? =) But actually nothing more than a bit of syntax sugar for spice, the grouper recipe is accomplished by the following expression.

*[iter(l)]*2

Which more or less translates to two arguments of the same iterator wrapped in a list, if that makes any sense. Lets break it down to help shed some light.

zip for shortest

>>> l*2 ['a', 'b', 'c', 'd', 'e', 'a', 'b', 'c', 'd', 'e'] >>> [l]*2 [['a', 'b', 'c', 'd', 'e'], ['a', 'b', 'c', 'd', 'e']] >>> [iter(l)]*2 [, ] >>> zip([iter(l)]*2) [(,),(,)] >>> zip(*[iter(l)]*2) [('a', 'b'), ('c', 'd')] >>> dict(zip(*[iter(l)]*2)) {'a': 'b', 'c': 'd'}

As you can see the addresses for the two iterators remain the same so we are working with the same iterator which zip then first gets a key from and then a value and a key and a value every time stepping the same iterator to accomplish what we did with the slices much more productively.

You would accomplish very much the same with the following which carries a smaller What the? factor perhaps.

>>> it = iter(l) >>> dict(zip(it, it)) {'a': 'b', 'c': 'd'}

What about the empty key e if you've noticed it has been missing from all the examples which is because zip picks the shortest of the two arguments, so what are we to do.

Well one solution might be adding an empty value to odd length lists, you may choose to use append and an if statement which would do the trick, albeit slightly boring, right?

>>> if len(l) % 2: ... l.append("") >>> l ['a', 'b', 'c', 'd', 'e', ''] >>> dict(zip(*[iter(l)]*2)) {'a': 'b', 'c': 'd', 'e': ''}

Now before you shrug away to go type from itertools import izip_longest you may be surprised to know it is not required, we can accomplish the same, even better IMHO, with the built in functions alone.

map for longest

I prefer to use the map() function instead of izip_longest() which not only uses shorter syntax doesn't require an import but it can assign an actual None empty value when required, automagically.

>>> l = ["a", "b", "c", "d", "e"] >>> l ['a', 'b', 'c', 'd', 'e'] >>> dict(map(None, *[iter(l)]*2)) {'a': 'b', 'c': 'd', 'e': None}

Comparing performance of the two methods, as pointed out by KursedMetal, it is clear that the itertools module far outperforms the map function on large volumes, as a benchmark against 10 million records show.

$ time python -c 'dict(map(None, *[iter(range(10000000))]*2))' real 0m3.755s user 0m2.815s sys 0m0.869s $ time python -c 'from itertools import izip_longest; dict(izip_longest(*[iter(range(10000000))]*2, fillvalue=None))' real 0m2.102s user 0m1.451s sys 0m0.539s

However the cost of importing the module has its toll on smaller datasets with map returning much quicker up to around 100 thousand records when they start arriving head to head.

$ time python -c 'dict(map(None, *[iter(range(100))]*2))' real 0m0.046s user 0m0.029s sys 0m0.015s $ time python -c 'from itertools import izip_longest; dict(izip_longest(*[iter(range(100))]*2, fillvalue=None))' real 0m0.067s user 0m0.042s sys 0m0.021s $ time python -c 'dict(map(None, *[iter(range(100000))]*2))' real 0m0.074s user 0m0.050s sys 0m0.022s $ time python -c 'from itertools import izip_longest; dict(izip_longest(*[iter(range(100000))]*2, fillvalue=None))' real 0m0.075s user 0m0.047s sys 0m0.024s

See nothing to it! =)

nJoy!

PythonServer Side ProgrammingProgramming

The list is a linear data structure containing data elements.

Example

1,2,3,4,5,6

Dictionary is a data structure consisting of key: value pairs. Keys are unique and each key has some value associated with it.

Example

1:2, 3:4, 5:6

Given a list, convert this list into the dictionary, such that the odd position elements are the keys and the even position elements are the values as depicted in the above example.

Method 1 − Iterating over the list

Example

 Live Demo

def convert(l):    dic={}    for i in range(0,len(l),2):       dic[l[i]]=l[i+1]    return dic ar=[1,'Delhi',2,'Kolkata',3,'Bangalore',4,'Noida'] print(convert(ar))

Output

{1: 'Delhi', 2: 'Kolkata', 3: 'Bangalore', 4: 'Noida'}

Method 2 − Using zip()

Initialize an iterator to the variable i. After that zip together the key and values and typecast into a dictionary using dict().

Example

 Live Demo

def convert(l):    i=iter(l)    dic=dict(zip(i,i))    return dic ar=[1,'Delhi',2,'Kolkata',3,'Bangalore',4,'Noida'] print(convert(ar))

Output

{1: 'Delhi', 2: 'Kolkata', 3: 'Bangalore', 4: 'Noida'}

Convert list to dict in python

Published on 11-Mar-2021 09:38:07

That’s 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 element’s 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 let’s 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 Python’s 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 element’s 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 that’s 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, Python’s 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, let’s 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 doesn’t 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 let’s 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.

Let’s 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 Python’s 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 – that’s 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 Python—while 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!