How to create a dictionary of lists in Python

In this post, we are going to learn How to create a dictionary of lists in Python with code examples. The list could not be used as dictionary keys. The Python dictionary can contain immutable datatype as keys (int, float, decimal, bool, string).

Let us understand how we can use the list as a value of dictionary keys

1. Create dictionary of lists using list append()

Here in this example, we are creating a dictionary by using the list in-built append() method. Here we will create a dictionary of the nested list as dictionary keys and values. Let us understand this with an example of how to achieve the same.

lang_dict = {}

lang_dict['mykey1'] = [1,2,3]

#creating a list to append

ani_list = ['rat','cat','bee','ant','worm']


lang_dict['mykey1'].append(ani_list)

print('dict with list append as values :\n',lang_dict)




Output

dict with list append as values :
 {'mykey1': [1, 2, 3, ['rat', 'cat', 'bee', 'ant', 'worm']]}

2. Create a dictionary of lists add list values to different key

Here in this example, we are adding two list values as different keys (mykey1,mykey2) of the dictionary. At ‘mykey1‘ key we have added list values [1,2,3] and at mykey2 we are adding list values [‘rat’, ‘cat’, ‘bee’].

lang_dict = {}


#adding list a value to "mykey1"
lang_dict['mykey1'] = [1,2,3]



#adding list a value to "mykey2"
lang_dict['mykey2'] = ['rat','cat','bee']



print('dict with list append as values :\n',lang_dict)

Output

dict with list append as values :
 {'mykey1': [1, 2, 3], 'mykey2': ['rat', 'cat', 'bee']}

3. Create dictionary of lists Using setdefault() add list values in range

Here, in this example, we are using the for loop over the elements of list num_list and creating a dictionary of lists using the range() method.

lang_dict = dict()
num_list = ['4','5','6']

for val in  num_list:
 for item in range(int(val), int(val) + 2):
        lang_dict.setdefault(item, []).append(val)          



print('dict with list  as values :\n',lang_dict)


Output

dict with list  as values :
 {4: ['4'], 5: ['4', '5'], 6: ['5', '6'], 7: ['6']}

4.Create a dictionary of List of tuples Using default_dict()

In this code example, we are converting a list of the tuple to dictionary values.In this ani_list tuple (‘rat’, 4),(‘rat’, 36) has the same key(‘rat’).So while converting to the dictionary, these will be combined as the ‘rat’ key. Because the key in the dictionary is unique.

from collections import defaultdict
  
ani_lst = [('rat', 4), ('cat', 5), ('rat', 36),('ant',37),('dog',37)]

my_dict = defaultdict(list)
  
# for loop t iterating over list of tuples

for key, value in ani_lst:
    my_dict[key].append(value)
  
print(f'the dictionary of lists :\n{my_dict}')


The Output will be:

the dictionary of lists :
defaultdict(<class 'list'>, {'rat': [4, 36], 'cat': [5], 'ant': [37], 'dog': [37]})