How to Convert Python List to Dictionary

0
1226
How To Convert Python List To Dictionary Example

Lists and dictionaries are Python collections that allow you to save similar values in one data structure. In addition, the list will enable you to save the data in a particular order, whereas dictionaries are unordered and cannot save multiple duplicate values.

Converting a list to a dictionary is Python’s standard operation. So let’s see how to do it.

Python list to dictionary

To convertlist to dictionary in Python, use the list comprehension and create a key-value pair of consecutive elements, and then typecast a list to dictionary type. The return value is converted from a list to a dictionary data 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 used the for loop to separate odd and even elements and then used the range() function to form the odd values to key and values to the dictionary. We have used the dictionary comprehension method.

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

Converting a list to dictionary with the same values

To convert a list to dictionary with the same values, use dictionary comprehension. Each key’s value will be the same.

# 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

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

Python list to dict using dict.fromKeys()

The dictionary.fromKeys() is a built-in Python method that 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 convert them to the dictionary keys. We pass the second parameter as 5, a 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 passed in fromkeys().

Converting list elements 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 values as an integer in 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

Converting two lists into a dictionary

To convert two lists to a dictionary in Python, use the zip() function, and it returns the list of tuples and passes that list of tuples to a dict() function, and it returns the 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 the 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

The zip() function accepts several iterable objects and returns the list of tuples.

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

We have passed two lists objects in zip() function, 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.

Converting the list of tuples to the dictionary in Python

To convert a list of tuples to the dictionary in Python, use the dict() method and pass the list of tuples to the dict() method, and it returns the dictionary.

# 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 the dictionary constructor.

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

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

That’s it for this tutorial.

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

Please enter your comment!
Please enter your name here

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