Get the data in the form that you need it

Python Data Structures
Python lists and dictionaries are two data structures in Python used to store data. A Python list is an ordered sequence of objects, whereas dictionaries are unordered. The items in the list can be accessed by an index (based on their position) whereas items in the dictionary can be accessed by keys and not by their position.
Let’s see how to convert a Python list to a dictionary.
Ten different ways to convert a Python list to a dictionary
- Converting a list of tuples to a dictionary
- Converting two lists of the same length to a dictionary
- Converting two lists of different length to a dictionary
- Converting a list of alternative key, value items to a dictionary
- Converting a list of dictionaries to a single dictionary
- Converting a list into a dictionary using enumerate()
- Converting a list into a dictionary using dictionary comprehension
- Converting a list to a dictionary using dict.fromkeys()
- Converting a nested list to a dictionary using dictionary comprehension
- Converting a list to a dictionary using Counter()
1. Converting a List of Tuples to a Dictionary
The dict()
constructor builds dictionaries directly from sequences of key-value pairs.
#Converting list of tuples to dictionary by using dict() constructor color=[('red',1),('blue',2),('green',3)] d=dict(color) print (d)#Output:{'red': 1, 'blue': 2, 'green': 3}
2. Converting Two Lists of the Same Length to a Dictionary
We can convert two lists of the same length to the dictionary using zip()
.
zip()
will return an iterator of tuples. We can convert that zip object to a dictionary using the dict()
constructor.
zip()
Make an iterator that aggregates elements from each of the iterables.
“
zip(*iterables)
: Returns an iterator of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables. The iterator stops when the shortest input iterable is exhausted. With a single iterable argument, it returns an iterator of 1-tuples. With no arguments, it returns an empty iterator.” — Python documentation
Example:
https://gist.github.com/IndhumathyChelliah/0a16b0b475cc2bc53fe1dafa86c840da

3.Converting Two Lists of Different Length to a Dictionary
We can convert two lists of different length to the dictionary using itertools.zip_longest()
.
As per Python documentation
“
zip_longest()
: Makes an iterator that aggregates elements from each of the iterables. If iterables are of uneven length, missing value is filled with fillvalue. Iteration continues until the longest iterable is exhausted.
In zip(),iteration continues until shortest iterable is exhausted.”
itertools.zip_longest(*iterables,fillvalue=None)
Using zip()
, iteration continues until the shortest iterable is exhausted.
https://gist.github.com/IndhumathyChelliah/a3ad3865e7dd7bf5863b1ecf015f27fe
Using zip_longest()
, iteration continues until the longest iterable is exhausted. By default, fillvalue
is None
.
https://gist.github.com/IndhumathyChelliah/328d97fd8ac1484c0608542f0edc0afc

fillvalue
is mentioned as x.
https://gist.github.com/IndhumathyChelliah/3bc1f13f6c305bee1fce3a51cca1e9c5
4. Converting a List of Alternative Key, Value Items to a Dictionary
We can convert a list of alternative keys, values as items to a dictionary using slicing.
Slicing returns a new list containing a sequence of items from the list. We can specify a range of indexes.
s[i:j:k] — slice of s from i to j with step k
We can create two slice lists. The first list contains keys alone and the next list contains values alone.
l1=[1,'a',2,'b',3,'c',4,'d']
Create two slice objects from this list.
The first slice object will contain keys alone
l1[::2]
start
is not mentioned. By default, it will start from the beginning of the list.
stop
is not mentioned. By default, it will stop at the end of the list.
stop
is mentioned as 2.
l1[::2]
Return a list containing elements from beginning to end using step 2 (alternative elements).
[1,2,3,4]

The second slice object will contain values alone
l1=[1,'a',2,'b',3,'c',4,'d']
l1[1::2]
start
is mentioned as 1. It will start slicing from the first index.
stop
is not mentioned. It will stop at the end of the list.
step
is mentioned as 2.
l1[1::2
] Return a list containing elements from the first index to the end using step 2 (alternative elements).
['a', 'b', 'c', 'd']

Now we can merge the two lists using the zip()
function.
https://gist.github.com/IndhumathyChelliah/6f8e4380eb1a59da3157b568114c615c
5. Converting a List of Dictionaries to a Single Dictionary
A list of dictionaries can be converted into a single dictionary by the following ways:
dict.update()
- dictionary comprehension
Collections.ChainMap
dict.update()
We can convert a list of dictionaries to a single dictionary using dict.update()
.
- Create an empty dictionary.
- Iterate through the list of dictionaries using a
for
loop. - Now update each item (key-value pair) to the empty dictionary using
dict.update()
.
https://gist.github.com/IndhumathyChelliah/828762fa72dc981344e4a90c4d2ace24
Dictionary comprehension
A dictionary comprehension consists of brackets{}
containing two expressions separated with a colon followed by a for
clause, then zero or more for
or if
clauses.
l1=[{1:'a',2:'b'},{3:'c',4:'d'}] d1={k:v for e in l1 for (k,v) in e.items()}
for e in l1
— Return each item in the list {1:’a’,2:’b’}
.
for (k,v) in e.items()
— Return the key, value pair in that item. (1,’a’)
(2,’b’)
k:v
— is updated in the dictionary d1
https://gist.github.com/IndhumathyChelliah/c81aac0512bdcf20545de3cc7fb05e95
Collections.ChainMap
By using collections.ChainMap()
, we can convert a list of dictionaries to a single dictionary.
As per the Python documentation
“
ChainMap
: A ChainMap groups multiple dictionary or other mappings together to create a single, updateable view.”
The return type will be ChainMap object
. We can convert to a dictionary using the dict()
constructor.
https://gist.github.com/IndhumathyChelliah/899ca0d75b21d11be00db94715a39751
6. Converting a List to a Dictionary Using Enumerate()
By using enumerate()
, we can convert a list into a dictionary with index as key and list item as the value.
enumerate()
will return an enumerate object.
We can convert to dict using the dict()
constructor.
As per the Python documentation:
“
enumerate(iterable, start=0)
: Returns an enumerate object. iterable must be a sequence, an iterator, or some other object which supports iteration. The__next__()
method of the iterator returned byenumerate()
returns a tuple containing a count (from start which defaults to 0) and the values obtained from iterating over iterable.
https://gist.github.com/IndhumathyChelliah/fd41136a52267c80af6a21301cf56d42
7. Converting List Into a Dictionary Using Dictionary Comprehension
By using dictionary comprehension, we can convert a list of keys to a dictionary having the same value.
d1={k:"a" for k in l1}
It will iterate through the list and change its item as a key (k
), and value will be a
for all keys.
https://gist.github.com/IndhumathyChelliah/7549281bc977cfce53f8da6e77524f57
8. Converting a List to a Dictionary Using dict.fromkeys()
dict.from keys()
will accept a list of keys, which is converted to dictionary keys, and a value, which is to be assigned.
The same value will be assigned to all keys.
https://gist.github.com/IndhumathyChelliah/7b7b147113185de5948d4d702b1b5150
9. Converting a Nested List to a Dictionary Using Dictionary Comprehension
We can convert a nested list to a dictionary by using dictionary comprehension.
l1 = [[1,2],[3,4],[5,[6,7]]]
d1={x[0]:x[1] for x in l1}
It will iterate through the list.
It will take the item at index 0 as key and index 1 as value.
https://gist.github.com/IndhumathyChelliah/9724776786cc5925e08ce545de5c435c
10. Converting a List to a Dictionary Using Counter()
“
Counter
: Counter is a dict subclass for counting hashable objects. It is a collection where elements are stored as dictionary keys and their counts are stored as dictionary values. Counts are allowed to be any integer value including zero or negative counts.” — Python documentation
collections.Counter(iterable-or-mapping)
Counter()
will convert list items to keys and their frequencies to values.
https://gist.github.com/IndhumathyChelliah/d97d10b1cbbd6f5418876d455a66a441
My other blog links
15 Things to Know to Master Python Dictionaries
Top 25 Questions on Python List
7 Different Ways to Merge Dictionaries in Python
Resources
Data Structures — Python 3.8.5 documentation
Make a one-time donation
Make a monthly donation
Make a yearly donation
Choose an amount
Or enter a custom amount
Your contribution is appreciated.
Your contribution is appreciated.
Your contribution is appreciated.
Buy Me a CoffeeBuy Me a CoffeeBuy Me a Coffee