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 tin combine them into i dictionary as well.

A dictionary, however, gives you more control over your data. So let'due south examine the different ways to convert lists into a dictionary in Python.

How to Catechumen a Single Listing to a Dictionary in Python

Provided that a list is symmetric (containing equal potential cardinal-value pairs), you can catechumen it to a dictionary using the for loop.

To do this, place your loop in a dictionary comprehension:

          1000 = ["frog", "dog", "Caprine animal", "true cat"]
d = {g[a]:one thousand[a + 1] for a in range(0, len(m), ii)}
print(d)
Output: {'frog': 'canis familiaris', 'Goat': 'true cat'}

The lawmaking may look complex at first, just it really isn't. You're only telling Python to pick a pair each time it iterates through your list. Then it should make every detail on the left of each pair the primal to the one on its right side, which is its value.

The integer (2) within the range parenthesis, however, ensures that your code simply accepts symmetric lists.

To sympathize its function, change the integer from 2 to 3. And so add together an particular to the listing earlier running your code.

To accomplish this without using the for loop, you can also utilize the built-in dict and zip functions of Python:

          a = iter(g) # spin up an iterator on the list
result = dict(zip(a, a)) # Convert the iterated items into central-value pairs
print(upshot)
Output: {'frog': 'dog', 'Goat': 'cat'}

Unlike the looping method that you used earlier, the dict(null()) function ignores whatever item without a pair.

For instance, if there are five items in a list, it ignores the fifth 1 and creates a matching primal-value pair with the first four items:

          grand = ["get-go", "second", "third", "quaternary", "fifth_odd"]
a = iter(m)
outcome = dict(zip(a, a))
print(outcome)
Output: {'first': 'second', 'third': 'fourth'}

How to Catechumen Two Lists of the Same Length Into a Lexicon

As earlier mentioned, you can convert two lists of equal length into a dictionary, making the items in 1 of them the keys, while the items in the other list serve every bit their corresponding values.

It isn't every bit catchy as converting a single list to a lexicon. Here'southward how to achieve this with the dict(nothing()) method:

          list1 = ["frog", "dog", "Caprine animal", "cat"]
list2 = [1, 3, 24, 56]
result = dict(zip(list2, list1))
print(result)
Output: {1: 'frog', iii: 'dog', 24: 'Caprine animal', 56: 'true cat'}

Y'all can also convert two lists into a dictionary using the for loop:

          list1 = ["frog", "canis familiaris", "Goat", "cat", "jog"]
list2 = [ane, 3, 24, 56
consequence = {list2[a]:list1[a] for a in range(len(list2))}
print(result)
Output: {ane: 'frog', 3: 'canis familiaris', 24: 'Goat', 56: 'cat'}

How to Convert Lists With Unequal Length to a Lexicon

If you lot're dealing with ii lists that take unlike lengths, you lot tin convert them into i dictionary too.

When y'all utilise the zip_longest module, Python assigns a nothing value to missing information. To apply this module, outset 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)
Output: {'True cat': i, 'Dogs': 4, 'Rats': half dozen, 'Fruits': None, 'ducks': None}

You can fill the missing values by including the fillvalue keyword:

          a = dict(zip_longest(list1, list2, fillvalue="10"))
impress(a)
Output: {'Cat': one, 'Dogs': 4, 'Rats': 6, 'Fruits': 'x', 'ducks': 'x'}

How to Convert a Nested List Into a Dictionary

A nested list is sometimes disruptive, just you can turn it into a lexicon besides.

For instance, it's easy to convert a list of paired tuples into a lexicon using the dict function:

          myList = [("Acquire", "MUO"), ("Python", "Google")]
myList = dict(myList)
print(myList)
Output: {'Learn': 'MUO', 'Python': 'Google'}

Converting a list of dictionaries into a single dictionary is a scrap different, but pretty easy besides:

          list1 = [{"True cat":"Dogs"}, {"Rats":"Fruits"}]
list1 = {a:b for i in list1 for a,b in i.items()}
print(list1)
Output: {'Cat': 'Dogs', 'Rats': 'Fruits'}

Agreement the concept of a lexicon gives you the fundamental knowledge of how arrays and JSON objects piece of work in programming. A dictionary, when invoked, makes items more callable in Python. In essence, information technology lets you telephone call whatever item past its cardinal. So you can admission 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 spider web requests. An example is when you lot become two columns every bit separate lists from the database and catechumen them into a lexicon or an array to make them more iterable, accessible, and piece of cake to manipulate.

Python Dictionary: How You Can Use Information technology To Write Ameliorate Code

Read Next

About The Author