AppDividend
Latest Code Tutorials

How To Convert Python List To Dictionary Example

0

In any language, data type conversion is the most common operation. In this tutorial, we will see How To Convert Python List To Dictionary Example. In this post, we will discuss different ways to convert single or multiple lists to the dictionary in Python.

Following conversions from the list to dictionary will be covered here,

  1. Convert the given list to dictionary such that all the odd elements have the key, and even number elements have the value. 
  2. Convert a List to Dictionary with the same values.
  3. Convert two lists to dictionary.
  4. Convert a list of tuples to the dictionary.

Python list To dictionary

Content Overview

We can convert a list to dict using list comprehension and make a key: value pair of consecutive elements. Finally, typecast the list to dict type.

See the following code example.

# app.py

def listToDict(lst):
    op = {lst[i]: lst[i + 1] for i in range(0, len(lst), 2)}
    return op


lst = ['m', 1, 'b', 2, 'k', 3]
print(listToDict(lst))

Output

➜  pyt python3 app.py
{'m': 1, 'b': 2, 'k': 3}
➜  pyt

In the above example, we have used the for loop to separate odd and even elements and then use the range() function to form the odd values to key and also values to the dictionary. We have used the dictionary comprehension method.

So, in the output, we get the dictionary converted from List.

Convert a List to Dictionary with the same values

Now we want to create a dictionary with all elements in this list as keys.

Each key’s value will be the same, for example. 5. Let’s see how to do that.

# app.py

def listToDict(lst):
    op = { i : 5 for i in lst }
    return op


lst = ['millie', 'caleb', 'finn', 'sadie', 'noah']
print(listToDict(lst))

See the output.

➜  pyt python3 app.py
{'millie': 5, 'caleb': 5, 'finn': 5, 'sadie': 5, 'noah': 5}
➜  pyt

In the above example, all the list elements became keys, and 5 is the value for all the elements.

Python list to dict using dict.fromKeys()

Python Dictionary fromKeys() method creates a new dictionary from a given sequence of elements with a value provided by a user.

The fromKeys method returns the dictionary with specified keys and values.

We are creating the dictionary from the list, so Python Dict fromKeys() can get the key values from the Python List and then convert it to the dictionary keys. We pass the second parameter as 5, which is value, so we get the same output as the above program.

# app.py

def listToDict(lst):
    op = dict.fromkeys(lst , 5)
    return op


lst = ['millie', 'caleb', 'finn', 'sadie', 'noah']
print(listToDict(lst))

Output

➜  pyt python3 app.py
{'millie': 5, 'caleb': 5, 'finn': 5, 'sadie': 5, 'noah': 5}
➜  pyt

The dict.fromKeys() accepts a list and default value. It returns a dictionary with items in the list as keys. All dictionary items will have the same value that was passed in fromkeys().

Convert List items as values in the dictionary with indexed keys in Python

In the first example of this article, we have used list items as keys and value as an integer of the dictionary. Still, in this example, we are creating a dictionary with indexed keys, and values are python list items using dictionary comprehension.

See the following code.

# app.py

def listToDict(lst):
    op = { i : lst[i] for i in range(0, len(lst) ) }
    return op


lst = ['millie', 'caleb', 'finn', 'sadie', 'noah']
print(listToDict(lst))

Output

➜  pyt python3 app.py
{0: 'millie', 1: 'caleb', 2: 'finn', 3: 'sadie', 4: 'noah'}
➜  pyt

How to convert two lists to dictionary

Let’s say we have two lists.

lstStr = ['millie', 'caleb', 'finn', 'sadie', 'noah']
lstInt = [11, 21, 19, 29, 46]

We will take the first list as the keys for the dictionary and the second list as values.

To achieve that and create a dictionary from two lists, we can use Python zip() function.

See the full code below.

# app.py

def listToDict(lstA, lstB):
    zippedLst = zip(lstA, lstB)
    op = dict(zippedLst)
    return op


lstStr = ['millie', 'caleb', 'finn', 'sadie', 'noah']
lstInt = [11, 21, 19, 29, 46]
print(listToDict(lstStr, lstInt))

See the output.

➜  pyt python3 app.py
{'millie': 11, 'caleb': 21, 'finn': 19, 'sadie': 29, 'noah': 46}
➜  pyt

Zip() accepts several iterable objects and returns the list of tuples.

Each entry in tuple contains an element from each iterable object.

We have passed two lists objects in zip(), so it will return a list of tuples, where each tuple contains an entry from both the lists. Then we created a dictionary object from this list of tuples.

If the length of the keys list is less than the list of values, then the remaining elements in the value list will be skipped.

Convert the list of tuples to dictionary in Python

See the following code.

# app.py

def listToDict(lstTup):
    op = dict(lstTup)
    return op


lstTuple = [('millie', 11), ('caleb', 21),
            ('finn', 19), ('sadie', 29), ('noah', 46)]
print(listToDict(lstTuple))

Output

➜  pyt python3 app.py
{'millie': 11, 'caleb': 21, 'finn': 19, 'sadie': 29, 'noah': 46}
➜  pyt

We can directly pass this list of tuples to dictionary constructor.

Entries in the first column will become the key, and entries in the second column will the values in the new dictionary. In the end, we achieve the goal of getting the dictionary from the tuple.

So, we have covered the variations of the Python list to a dictionary conversion.

Related Posts

Python string to int and int to string

Python string to list and list to string

Python dictionary to json

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.