Converting a list to a dictionary is helpful if you want to create a key-value pair from that list. And if there are two lists, you can combine them into one dictionary as well.
A dictionary, however, gives you more control over your data. So let's examine the different ways to convert lists into a dictionary in Python.
How to Convert a Single List to a Dictionary in Python
Provided that a list is symmetric (containing equal potential key-value pairs), you can convert it to a dictionary using the for loop.
To do this, place your loop in a dictionary comprehension:
m = ["frog", "dog", "Goat", "cat"]
d = {m[a]:m[a + 1] for a in range(0, len(m), 2)}
print(d)
<strong>Output:</strong> {'frog': 'dog', 'Goat': 'cat'}
The code may look complex at first, but it actually isn't. You're only telling Python to pick a pair each time it iterates through your list. Then it should make every item on the left of each pair the key to the one on its right side, which is its value.
The integer (2) within the range parenthesis, however, ensures that your code only accepts symmetric lists.
To understand its function, change the integer from 2 to 3. Then add an item to the list before running your code.
To achieve this without using the for loop, you can also use the built-in dict and zip functions of Python:
a = iter(m) # spin up an iterator on the list
result = dict(zip(a, a)) # Convert the iterated items into key-value pairs
print(result)
<strong>Output:</strong> {'frog': 'dog', 'Goat': 'cat'}
Unlike the looping method that you used earlier, the dict(zip()) function ignores any item without a pair.
For instance, if there are five items in a list, it ignores the fifth one and creates a matching key-value pair with the first four items:
m = ["first", "second", "third", "fourth", "fifth_odd"]
a = iter(m)
result = dict(zip(a, a))
print(result)
<strong>Output:</strong> {'first': 'second', 'third': 'fourth'}
How to Convert Two Lists of the Same Length Into a Dictionary
As earlier mentioned, you can convert two lists of equal length into a dictionary, making the items in one of them the keys, while the items in the other list serve as their corresponding values.
It isn't as tricky as converting a single list to a dictionary. Here's how to achieve this with the dict(zip()) method:
list1 = ["frog", "dog", "Goat", "cat"]
list2 = [1, 3, 24, 56]
result = dict(zip(list2, list1))
print(result)
<strong>Output:</strong> {1: 'frog', 3: 'dog', 24: 'Goat', 56: 'cat'}
You can also convert two lists into a dictionary using the for loop:
list1 = ["frog", "dog", "Goat", "cat", "jog"]
list2 = [1, 3, 24, 56
result = {list2[a]:list1[a] for a in range(len(list2))}
print(result)
<strong>Output:</strong> {1: 'frog', 3: 'dog', 24: 'Goat', 56: 'cat'}
How to Convert Lists With Unequal Length to a Dictionary
If you're dealing with two lists that have different lengths, you can convert them into one dictionary as well.
When you use the zip_longest module, Python assigns a null value to missing data. To use this module, first import it into your code:
from itertools import zip_longest
list1 = ["Cat", "Dogs", "Rats", "Fruits", "ducks"]
list2 =[1, 4, 6]
a = dict(zip_longest(list1, list2))
print(a)
<strong>Output:</strong> {'Cat': 1, 'Dogs': 4, 'Rats': 6, 'Fruits': None, 'ducks': None}
You can fill the missing values by including the fillvalue keyword:
a = dict(zip_longest(list1, list2, fillvalue="10"))
print(a)
<strong>Output:</strong> {'Cat': 1, 'Dogs': 4, 'Rats': 6, 'Fruits': '10', 'ducks': '10'}
How to Convert a Nested List Into a Dictionary
A nested list is sometimes confusing, but you can turn it into a dictionary as well.
For instance, it's easy to convert a list of paired tuples into a dictionary using the dict function:
myList = [("Learn", "MUO"), ("Python", "Google")]
myList = dict(myList)
print(myList)
<strong>Output:</strong> {'Learn': 'MUO', 'Python': 'Google'}
Converting a list of dictionaries into a single dictionary is a bit different, but pretty easy as well:
list1 = [{"Cat":"Dogs"}, {"Rats":"Fruits"}]
list1 = {a:b for i in list1 for a,b in i.items()}
print(list1)
<strong>Output:</strong> {'Cat': 'Dogs', 'Rats': 'Fruits'}
Dictionary Is a Valuable Python Tool
Understanding the concept of a dictionary gives you the fundamental knowledge of how arrays and JSON objects work in programming. A dictionary, when invoked, makes items more callable in Python. In essence, it lets you call any item by its key. So you can access its matching value.
That said, converting a list to a dictionary in Python is helpful in many real-life cases. Ultimately, a dictionary also confers speed on web requests. An example is when you get two columns as separate lists from the database and convert them into a dictionary or an array to make them more iterable, accessible, and easy to manipulate.