Skip to content
Related Articles
Open in App
Not now

Related Articles

Python | Ways to create a dictionary of Lists

Improve Article
Save Article
  • Difficulty Level : Medium
  • Last Updated : 30 Dec, 2022
Improve Article
Save Article

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

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 dictionary. Let’s see all the different ways we can create a dictionary of Lists. Method #1: Using subscript 

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]}

  Method #2: Adding nested list as value using 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']]}

  Method #3: Using setdefault() method Iterate the list and keep appending the elements till given range using 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']}

  Method #4: Using list comprehension 

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]}

  Method #5: Using defaultdict Note that the same thing can also be done with simple dictionary but using defaultdict is more efficient for such cases. 

Python3




# Importing defaultdict
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]})

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

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)
 
#Added by Paras Jain(everythingispossible)

Output:

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

 Method #6:  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.

Here’s an example of using zip_longest to create a dictionary of lists:

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']}

This approach has a time complexity of O(n) and a space complexity of O(n), where n is the length of the longest list.


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!