A dictionary in Python is a collection of data stored in the form of key-value pairs. We can assign different data types as values for keys. It helps coders store data and category genres and build the database accordingly.
On the other hand, lists also store data, but here the elements are not associated with multiple values. Dictionaries and lists are both indexed. In lists, we store data in the form of sequences, and these sequences can be traversed and manipulated.
In this article, we will merge these two formats and create a dictionary of lists. Before we dive into the topic, let’s take a quick overview of this article.
For dictionary creation, we use "{}" curly brackets. Let's look at the syntax -
dict1 = {"Car": "AUDI"}
Here "Car" is the key and "AUDI" is the key value.
For list creation, we use "[]" square brackets. Let's look at the syntax -
lis1 = ["Name", "age", "gender", "qualification"]
Here, "name", "age", "gender", and "qualification" are elements of the list "lis1".
When we try to combine these formats to generate a dictionary of lists, this means we have to treat the list as a key-value pair. But the question is whether the list acts as keys or values. The rule for assigning a key is that it should be "immutable" or unchangeable.
Therefore, a list cannot serve as a dictionary key. So when dealing with a dictionary of lists, we treat lists as "values" of immutable keys.
In this method we directly name the keys and assign them a list of values. Let's see its implementation -
dict1 = {} dict1["Name"] = ["RAM", "RAVI", "TARUN", "MOHAN"] #assigning 1st key dict1["Age"] = [22, 23, 18, 27] #assigning 2nd key print(dict1)
{'Name': ['RAM', 'RAVI', 'TARUN', 'MOHAN'], 'Age': [22, 23, 18, 27]}
Here, we create an empty dictionary and then assign the key values externally. "Name" is the first key and "Age" is the second key.
If we reverse the order, i.e. we specify list as the key of this dictionary, then let's see what happens -
dict1 = {["Name", "Age", "Gender"]: "RAVI"}
dict1 = {["Name", "Age", "Gender"]: "RAVI"} TypeError: unhashable type: 'list'
throws an error because lists are not immutable by nature and therefore cannot be used as keys.
Both the dict() and defaultdict methods can be used to generate list dictionaries. Let's see the implementation -
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)
defaultdict(<class 'list'>, {'Name': ['Arjun', 'RAVI', 'ADITYA'], 'Age': [22, 23, 28]})
The interesting thing about this method is that it allows list information to be passed in brackets for each value. This means that for a given bracket, we can only pass one key value.
If we want to increase the key value, we need 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 in the correct order of information. We use the defaultdict method to do this because it is more efficient and creates a default value in case a key is missing. We iterate through the list and append each key and value pair to the dictionary.
setdeafault() method is used to return the dictionary value associated with the given key. The unique thing about this method is that if the specified key does not exist, then it creates that specific key by inserting it. Let's see the implementation -
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)
{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 for each key. The problem with this approach is the choice of data type, only numeric entries can be considered range values.
here,
We create an empty dictionary and then pass it a list in which the information is stored.
We iterate over the list and separate keys and values. We create each numeric entry as a key and then after using another "for loop" we set the range for value initialization.
We append the values and their keys to the empty dictionary.
Finally, we print the dictionary.
In this article, we learned the basic concepts of dictionary creation and processing. We discussed various methods of creating a dictionary of lists and looked at the complexities and limitations of each method.
The above is the detailed content of How to create a dictionary of lists in Python. For more information, please follow other related articles on the PHP Chinese website!