Friday, December 27, 2024
Google search engine
HomeLanguagesPython | Ways to create a dictionary of Lists

Python | Ways to create a dictionary of Lists

Till now, we have seen the ways to create a dictionary in multiple ways and different operations on the key and values in the Python dictionary. Now, let’s see different ways of creating a dictionary of lists. Note that the restriction with keys in the Python dictionary is only immutable data types can be used as keys, which means we cannot use a dictionary of lists as a key. 

Example:

Input: myDict = {}
myDict["key1"] = [1, 2] # Adding list as value
myDict["key2"] = ["Geeks", "For", "Geeks"]
Output: {'key2': ['Geeks', 'For', 'Geeks'], 'key1': [1, 2]}
Explanation: In the output, we have a dictionary of lists.

Problem Statement

We generally got the typrerror if we try to implement it in the normal way.

Python3




# Creating a dictionary
myDict = {[1,2]: 'Geeks'}
 
print(myDict)


Output:

TypeError: unhashable type: 'list'

But the same can be done very wisely with values in a dictionary. Let’s see all the different ways we can create a dictionary of Lists. 

Ways to Create a Dictionary of Lists

Below are the topics that we will cover in this article:

Create a Dictionary of Lists using subscript

This code initializes an empty dictionary myDict. It then adds two key-value pairs to the dictionary: "key1" with the value [1, 2], and "key2" with the value ["Geeks", "For", "Geeks"]. Finally, the code prints the contents of the dictionary.

Python3




# Creating an empty dictionary
myDict = {}
 
# Adding list as value
myDict["key1"] = [1, 2]
myDict["key2"] = ["Geeks", "For", "Geeks"]
 
print(myDict)


Output:

{'key2': ['Geeks', 'For', 'Geeks'], 'key1': [1, 2]}

Time complexity: O(1) for each dictionary insertion and printing the dictionary.
Auxiliary space: O(n), where n is the total number of elements in the dictionary. 

Create a dictionary of Lists using the append() method

Adding nested list as a value using the append() method. Create a new list and we can simply append that list to the value. 

Python3




# Creating an empty dictionary
myDict = {}
 
# Adding list as value
myDict["key1"] = [1, 2]
 
# creating a list
lst = ['Geeks', 'For', 'Geeks']
 
# Adding this list as sublist in myDict
myDict["key1"].append(lst)
 
print(myDict)


Output:

{'key1': [1, 2, ['Geeks', 'For', 'Geeks']]}

Time complexity: O(1).
Auxiliary space complexity: O(n). 

Create a dictionary of Lists using the setdefault() Method

Iterate the list and keep appending the elements till the given range using the setdefault() method. 

Python3




# Creating an empty dict
myDict = dict()
 
# Creating a list
valList = ['1', '2', '3']
 
# Iterating the elements in list
for val in valList:
    for ele in range(int(val), int(val) + 2):
        myDict.setdefault(ele, []).append(val)
 
print(myDict)


Output:

{1: ['1'], 2: ['1', '2'], 3: ['2', '3'], 4: ['3']}

Time complexity : O(n^2)
Space complexity : O(n)

Creating dictionary of lists using List Comprehension 

In list comprehension we iterate over the values '1', '2', and '3', and for each value, it creates a key-value pair in the dictionary. The key is the current value, and the value is a range of integers starting from the value converted to an integer and ending at the value plus 1.

Python




# Creating a dictionary of lists using list comprehension
d = dict((val, range(int(val), int(val) + 2))
                  for val in ['1', '2', '3'])
 
print(d)


Output:

{'1': [1, 2], '3': [3, 4], '2': [2, 3]}

Time complexity: O(1).
Auxiliary space complexity: O(n). 

Creating dictionary of lists using defaultdict

Import the defaultdict class from the collections module. Define a list of tuples lst with each tuple containing a key-value pair. Create a defaultdict object called orDict that will have default values of an empty list. Iterate over the list of tuples lst using a for loop and unpack each tuple into the key and val variables. Append the value val to the list associated with the key in the orDict dictionary.

Print the resulting or Dict dictionary.

Note: The same thing can also be done with a simple dictionary but using defaultdict is more efficient for such cases. 

Python3




from collections import defaultdict
 
lst = [('Geeks', 1), ('For', 2), ('Geeks', 3)]
orDict = defaultdict(list)
 
# iterating over list of tuples
for key, val in lst:
    orDict[key].append(val)
 
print(orDict)


Output:

defaultdict(, {'For': [2], 'Geeks': [1, 3]})

Time complexity: O(n).
Auxiliary space: O(n). 

Note that there are only two key: value pairs in the output dictionary but the input list contains three tuples. The first element(i.e. key) is the same for the first and third tuples and two keys can never be the same.   

Creating a dictionary of lists using Json 

By importing the json module. It initializes a list lst containing tuples. Then, an empty dictionary dict is initialized. The code converts the list lst into a JSON formatted string using json.dumps(), and assigns this string as a key in the dictionary dict with the value “converted”. Finally, the dictionary is printed.

Python3




#importing json
import json
 
#Initialisation of list
lst = [('Geeks', 1), ('For', 2), ('Geeks', 3)]
 
#Initialisation of dictionary
dict = {}
 
#using json.dump()
hash = json.dumps(lst)
 
#creating a hash
dict[hash] = "converted"
 
#Printing dictionary
print(dict)


Output:

{'[["Geeks", 1], ["For", 2], ["Geeks", 3]]': 'converted'}

Time complexity: O(n), where n is the length of the list lst.
Auxiliary space: O(n), where n is the length of the list lst.

Creating dictionary of lists using itertools

One approach is to use the zip_longest function from the itertools module. This function allows you to iterate over two or more iterables in a parallel fashion, filling in any missing elements with a specified fill value.

Python3




from itertools import zip_longest
 
# Initialize the lists
list1 = [1, 2, 3]
list2 = [10, 20, 30, 40]
list3 = ['a', 'b', 'c', 'd', 'e']
 
# Use zip_longest to iterate over the lists in parallel
d = {}
for elem1, elem2, elem3 in zip_longest(list1, list2, list3, fillvalue=0):
    d.setdefault(elem1, []).append(elem2)
    d.setdefault(elem1, []).append(elem3)
 
print(d)
# Output: {1: [10, 'a'], 2: [20, 'b'], 3: [30, 'c'], 0: [40, 'd']}


Output

{1: [10, 'a'], 2: [20, 'b'], 3: [30, 'c'], 0: [40, 'd', 0, 'e']}

Time complexity: O(n), where n is the length of the longest list.
Auxiliary space: O(n)

RELATED ARTICLES

Most Popular

Recent Comments