Ways to create a dictionary of lists in python


A dictionary in python is a collection of data stored in the form of key value pair. We can assign different datatypes as the value for a key. It helps the coder to store data and categories genres and build databases accordingly.

List on the other hand also stores data but here elements are not associated with multiple values. Both dictionaries and lists are indexed. In list we store data in the form of sequences and these sequences can be traversed and manipulated.

In this article we will merge the two formats together and create a dictionary of lists. Before we dive deep into the topic, let’s quickly go through the overview of this article.

Creating a dictionary

For dictionary creation we use “{}” curly braces. Let’s see the syntax −

dict1 = {"Car": "AUDI"}

Here “Car” is the key and “AUDI” is the key value.

Creating a list

For listcreation we use “[]” square braces. Let’s see the syntax −

lis1 = ["Name", "age", "gender", "qualification"]

Here, “Name”, “age”, “gender”, “qualifications” are elements of the list- “lis1”.

When we try to combine these formats to produce a dictionary of list, it means we have to treat lists as a key value pair. But the question is whether a list acts as a key or a value. The rule for assigning a key is that it should be “immutable” or unchangeable.

Therefore, a list cannot act as a key for a dictionary. So, while handling a dictionary of lists we will treat the list as the “value” for an immutable key.

Different ways to create a dictionary of lists

Assinging list as value in the form of subscript

In this method we directly name the keys and assign them a list of values. Let’s see its implementation −

Example

dict1 = {}
dict1["Name"] = ["RAM", "RAVI", "TARUN", "MOHAN"] #assigning 1st key
dict1["Age"] = [22, 23, 18, 27] #assigning 2nd key
print(dict1)

Output

{'Name': ['RAM', 'RAVI', 'TARUN', 'MOHAN'], 'Age': [22, 23, 18, 27]} 

Here, we created an empty dictionary and then assigned the key values externally. “Name” is the 1st key and “Age” is the second key.

If we reverse the order i.e., we assign list as the key for this dictionary then let’s see what happens −

Example

dict1 = {["Name", "Age", "Gender"]: "RAVI"}

Output

dict1 = {["Name", "Age", "Gender"]: "RAVI"}
TypeError: unhashable type: 'list'  

An error is raised because lists are not immutable in nature and therefore cannot be used as a key.

Using the dict or defaultdict method

Both dict() and defaultdict method can be used to produce a dictionary of lists. Let’s see the implementation −

Example

from collections import defaultdict
lis1 = [("Name", "Arjun"), ("Age", 22), ("Age", 23), ("Age", 28), ("Name", "RAVI"),("Name", "ADITYA")]
dict1 = defaultdict(list)
for keys, values in lis1:
   dict1[keys].append(values)
print(dict1)

Output

defaultdict(<class 'list'>, {'Name': ['Arjun', 'RAVI', 'ADITYA'], 'Age': [22, 23, 28]})
  • The interesting aspect of this method is that it allows the list information to be passed in a bracket per value form. This means that for a given bracket we can only pass a single key value.

  • If we want to increase the key value, we would require a new bracket with the correct key name. this increases the readability of the program.

  • Here, we imported the collections module to use the “defaultdict” method. We passed the list with the correct information order. We used defaultdict approach to perform this operation because it is much more efficient and creates a default value in-case of missing keys atrocities. We traversed through the list and appended each key and value pair inside a dictionary.

Using set default method

The setdeafault() method is used to return a dictionary value associated with the given key. The uniqueness of this method is that, if the specified key does not exist then it creates that particular key through insertion. Let’s see the implementation −

Example

dict1 = {}
lis1 = [23, 24, 28, 12, 22]
for key in lis1:
   for values in range(int(key), int(key)+4):
      dict1.setdefault(values, []).append(key)
print(dict1)

Output

{23: [23, 22], 24: [23, 24, 22], 25: [23, 24, 22], 26: [23, 24], 27: [24], 28: [28], 29: [28], 30: [28], 31: [28], 12: [12], 13: [12], 14: [12], 15: [12], 22: [22]}

Using this method, we can create a record of each key. The problem with this approach is the selection of data type, only a numeric entry can be considered as the range value.

Here,

  • We created an empty dictionary and then passed a list with the information stored in it.

  • We iterated through the list and segregated the keys and values. We created each numeric entry as the key and then after using another “for loop” we set up a range for the value initialisation.

  • We appended the values and their keys in the empty dictionary.

  • At last, we printed the dictionary.

Conclusion

In this article we learned about the basic concepts of dictionary creation and handling. We discussed the various methods to create a dictionary of lists and understood the complications and limitations of each method.

Updated on: 27-Feb-2023

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements