The Wayback Machine - https://web.archive.org/web/20230616092626/https://www.geeksforgeeks.org/python-convert-a-list-to-dictionary/
Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App
geeksforgeeks
Browser
Continue

Related Articles

Python | Convert a list to dictionary

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

Given a list, write a Python program to convert the given list to dictionary such that all the odd elements have the key, and even number elements have the value. Since python dictionary is unordered, the output can be in any order.

Examples: 

Input : ['a', 1, 'b', 2, 'c', 3]
Output : {'a': 1, 'b': 2, 'c': 3}
Input : ['Delhi', 71, 'Mumbai', 42]
Output : {'Delhi': 71, 'Mumbai': 42}

Method #1: dict comprehension

To convert a list to dictionary, we can use list comprehension and make a key:value pair of consecutive elements. Finally, typecase the list to dict type. 

Python3




# Python3 program to Convert a
# list to dictionary
 
def Convert(lst):
    res_dct = {lst[i]: lst[i + 1] for i in range(0, len(lst), 2)}
    return res_dct
         
# Driver code
lst = ['a', 1, 'b', 2, 'c', 3]
print(Convert(lst))

Output

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

Time complexity: O(n), where n is the length of the input list.

Auxiliary space: O(n), where n is the length of the input list.

Method #2 : Using zip() method

First create an iterator, and initialize it to variable ‘it’. Then use zip method, to zip keys and values together. Finally typecast it to dict type. 

Python3




# Python3 program to Convert a
# list to dictionary
 
 
def Convert(a):
    it = iter(a)
    res_dct = dict(zip(it, it))
    return res_dct
 
 
# Driver code
lst = ['a', 1, 'b', 2, 'c', 3]
print(Convert(lst))

Output

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

Time complexity: O(n), where n is the length of the input list a. 
Auxiliary space: O(n), where n is the length of the input list a. 

Method #3 : Using zip() method

First, create an array of keys and values by using array slicing. Then use the map method to form array of tuple with key value paris. Finally typecast it to dict type. 

Python




# Python3 program to Convert a
# list to dictionary
 
 
def Convert(lst):
    res_dct = map(lambda i: (lst[i], lst[i+1]), range(len(lst)-1)[::2])
    return dict(res_dct)
 
 
# Driver code
lst = ['a', 1, 'b', 2, 'c', 3]
print(Convert(lst))

Output

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

Time complexity: O(n), where n is the number of key-value pairs in the dictionary.
Auxiliary space: O(n), to store the keys and values in dictionary.

Method #4: Using a loop

This method works by initializing an empty dictionary and then iterating through the list in steps of 2. In each iteration, the key-value pair is added to the dictionary using the current element as the key and the next element as the value. Finally, the dictionary is returned as the result.

steps: 

  1. Define a function named convert() that takes a single parameter lst as input.
  2. Initialize an empty dictionary named res_dict to store the key-value pairs.
  3. Use a for loop to iterate over the list lst with a step of 2. This means that the loop variable i will take on the values 0, 2, 4, etc.
  4. For each value of i, add a new key-value pair to the res_dict dictionary. The key is the i-th element of the list lst, and the value is the i+1-th element of the list lst.
  5. Once the loop has finished iterating over all the pairs of elements in the list, return the resulting dictionary res_dict.
  6. Create a list named lst containing alternating strings and integers.
  7. Call the convert() function with lst as input.
  8. Print the resulting dictionary.

Python3




def convert(lst):
    res_dict = {}
    for i in range(0, len(lst), 2):
        res_dict[lst[i]] = lst[i + 1]
    return res_dict
 
lst = ['a', 1, 'b', 2, 'c', 3]
print(convert(lst))

Output

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

Time complexity: O(n), where n is the length of the input list. 
Auxiliary space: O(n), where n is the length of the input list.

Method #5: Using itertools

Step-by-step approach:

  • Import the itertools module.
  • Use the zip_longest() function to create a list of tuples from the original list. This function will group the elements into pairs, even if the length of the list is odd.
  • Use a dictionary comprehension to create a dictionary from the list of tuples.
  • Return the dictionary.

Below is the implementation of the above approach:

Python3




import itertools
 
def convert(lst):
    pairs = itertools.zip_longest(*[iter(lst)] * 2, fillvalue=None)
    dct = {key: value for key, value in pairs}
    return dct
 
lst = ['a', 1, 'b', 2, 'c', 3]
print(convert(lst))

Output

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

Time complexity: O(n)
Auxiliary space: O(n) (to store the list of tuples)

Method 6: using list comprehension and slicing

Step-by-step approach:

  • Slice the input list to get a list of keys by using lst[::2]. This will take every second element starting from the first element of the list.
  • Slice the input list to get a list of values by using lst[1::2]. This will take every second element starting from the second element of the list.
  • Create a dictionary by using a dictionary comprehension that iterates over the indices of the keys list and pairs each key with its corresponding value from the values list.
  • Return the resulting dictionary.

Below is the implementation of the above approach:

Python3




def convert(lst):
    keys = lst[::2]  # slice the list to get keys
    values = lst[1::2]  # slice the list to get values
    res_dict = {keys[i]: values[i] for i in range(len(keys))}
    return res_dict
lst = ['a', 1, 'b', 2, 'c', 3]
print(convert(lst))  # {'a': 1, 'b': 2, 'c': 3}

Output

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

Time complexity: O(n)
Auxiliary space: O(n).


Last Updated : 27 Apr, 2023
Like Article
Save Article
Similar Reads
Related Tutorials