Python Dictionary of Lists[9 ways]

Are you looking for a way to create a Python dictionary of lists? In this Python tutorial, we will explain 9 different methods and approaches with real-time scenarios and examples.

While working on a Python project, I encountered a requirement to store user data like username, email, password, and age in a dictionary datatype(key-value pair).

This is only possible when we create a dictionary of lists. So, the key will be the username, and the value will be the list of other data.

While researching, I found 8 different methods to create lists in the Python dictionary. I thought I would share them with you so you can use them in this type of situation.

9 Ways to Create Python Dictionary of Lists

Let’s understand the scenario with one small example so you’ll get more clarity on where you should use these approaches.

So before creating the dictionary, we have the data like this:

username_1 = ['email', 'password', 'age']
username_2 = ['email', 'password', 'age']

But what if the millions of users will be there? It will be more complex to manage all the different lists. That’s why we need to create the dictionary so we can store data in key-value pairs like this:

users_data = {
    "username_1" : ['email', 'password','age'],
    "username_2" : ['email', 'password','age'],
}

So, these methods will help you in this kind of scenario when working on real-time projects.

Let’s understand all these methods one by one with practical examples:

How to create a dictionary of lists in Python using dictionary literals

First, we will show you how to create the list directly inside the dictionary and also explain how to use the list elements inside the dictionary.

Syntax

var_name = {
    "key_name": [value1, value2, val3 .......],
}
  • This syntax will be useful when we need to create Python dict of lists.
employee_ratings = {
    'James': [72, 63, 87],
    'Adam': [56, 65, 69],
    'John': [88, 79, 84]
}
print(f"Dictionary is : \n",employee_ratings,"\n\n")

for x in employee_ratings.items():
    name, rating = x
    avg = sum(rating)/len(rating)
    print('Average rating of', name, 'is', avg)
How to create a dictionary of lists in Python using dictionary literals

In the above code, we are creating a dictionary where the key is the employee’s name, and the values are given as a rating of the three months of employees in the list.

So here we are, creating the list of ratings directly inside the employee_rating dictionary. Then, we calculate the average rating for three months and describe that
for x in employee_ratings.items()” we can use the element of lists of dictionaries in Python.

READ:  Python dictionary multiple keys

Create a Python dict of lists using dict() & zip() methods

In the situation where there are two different lists, and you need to create the dictionary and include those lists in key-value pairs, then you can use the dict() and zip() methods.

The zip() method is used to combine multiple collections in one object and return the elements in the pairs of tuples. Suppose there are two lists, list_1 = [1,2,3] and
list_2 = [4,5,6]. If you use the zip method like this list(zip(list_1, list_2)), it will return
[(1, 4), (2, 5), (3, 6)].

The dict() is a constructor in Python which is used to define a dictionary in Python.

Syntax

dict(zip(list_1, list_2))
  • dict(zip(list_1, list_2)): This syntax will help create the list in the dictionary.

Let’s understand with a practical example to create a Python Dictionary of Lists.

username = ['James', 'Adam', 'John']

user_data = [
    ['jms@gmail.com', 2641, 26],
    ['adm@gmail.com', 4521, 39],
    ['jhn@gmail.com', 8965, 42]
]
database = dict(zip(username, user_data ))

print(database)
Create a Python dict of lists using dict() & zip() methods

In the above code, we have two different lists named username and user_data, where values are available as nested lists, so I need to make the dictionary where username should be the key and user_data should be the values in the list.

So we created a dictionary named database and used the dict and zip() methods like this: database = dict(zip(username, user_data )).

Create a list in a dictionary Python using a dictionary comprehension

In Python, dictionary comprehension is the process of creating a dictionary from existing data. So, we will use a one-liner for a loop in dictionary comprehension to iterate over the elements of the list individually and include them in the dictionary one by one.

Syntax

dictionary_name = {key[i]: value[i] for i in range(len(key))}

Here’s an example of creating a Python Dictionary of Lists using dictionary comprehension.

username = ['James', 'Adam', 'John']

user_data = [
    ['jms@gmail.com', 2641, 26],
    ['adm@gmail.com', 4521, 39],
    ['jhn@gmail.com', 8965, 42]
]
database = {username[i]: user_data[i] for i in range(len(username))}
print(database)
Create list in a dictionary Python using a dictionary comprehension

In the above code, we have taken the same scenario in this example as we took in the previous program, but this time, we will create the dictionary of lists using dictionary comprehension in Python.

So first, a one-liner for loop will be executed “ for i in range(len(username)),” where “i” will iterate over every element of the list, like this username[i]: user_data[i], and add the elements to the dictionary.

How to create Python dict of the list using defaultdict() method

Generally, the defaultdict() method is used to handle the errors; if we try to access the value of the key that does not exist, then instead of giving a key error, it will return the default value of the datatype, which we will give as a parameter of defaultdict().

So, we will create a dictionary of lists using the defaultdict() method in Python and include the values in the lists using the append() method.

Syntax

var_name = defaultdict(datatype)
  • In this topic, we will use defaultdict(list) because we need to create the Python dictionary of lists.
READ:  Python dictionary length - Everything you need to know

Code:

from collections import defaultdict

usa_info = defaultdict(list)

usa_info['Cities'].append('Austin')
usa_info['Cities'].append('Seattle')
usa_info['States'].append('California')
usa_info['States'].append('Texas')

print(usa_info)
How to create Python dict of list using defaultdict() method

In the above code, we created a dictionary named “usa_info”, where we assigned the defaultdict(list). Then we append the city names like “Austin” or “Seattle” into the key “Cities” like this: “usa_info[‘Cities’].append(‘Austin’)“. \

But there is no key like “Cities” in the dictionary, so it should give me a KeyError. Instead of getting the KeyError, it creates the key named “Cities” and includes the city names in the list.

Dictionary of the list in Python using for loop and update() method

We can also use the for loop with update() method to create the Python dictionary of lists. So, the for loop will be useful for iterating the elements of both lists together, and then we will include it in a dictionary using the dict.update() method in Python.

Let’s execute the code to understand How a Python Dictionary of Lists can be created using a for loop and the update method.

Syntax of update() method

dict.update({key: value})
customer_purchase = {}

customer_names = ["James", "Peter","John","George"]

purchase_amount = [[50, 54, 76],[ 92, 89, 52], [67, 74, 85],[ 78, 56, 42]]

for i in range(len(customer_names)):
    customer_purchase.update({customer_names[i]: purchase_amount[i]})

print(customer_purchase)
Dictionary of list in Python using for loop and update() method

In the above code, we have a list of customer names and a list of lists of the purchase amounts for three days. Now, I need to create a dictionary where names will be the keys and the three days of purchase amount should be the value.

So we used a for loop, where we initialized “i” and gave the range() as a length of customer names like this: for i in range(len(customer_names)). Then, we used the update() method to add the customer names as a key and the purchase amount as a list of values like this: customer_purchase.update({customer_names[i]: purchase_amount[i]})

Lists in dictionary Python using setdefault() method

We can also use the setdefault() method to create the Python Dictionary of Lists. This method takes two parameters as key and value so that it will add the pair in the dictionary.

So, we will use this method to include the list in dict and add the values using the append() method.

Syntax

dict.setdefault('key', []).append(value)
  • So, we will use this syntax to create the list inside the dictionary using the setdefault() method

Example of creating a Python Dictionary of Lists:

customer_purchase = {} 

purchase_amount = [76, 67, 81]

for index in purchase_amount:
    customer_purchase.setdefault('James', []).append(index)
    
print(customer_purchase)
Lists in dictionary Python using setdefault() method

In the above code, we initialized the empty dictionary, created a list of purchase_amount, and then initialized the for loop to target all elements of the purchase amount. And using setdefault() like this: customer_purchase.setdefault(‘James’, []).append(index) to add “James” as a key and purchase amount as a value.

Python dictionary of lists using dict.fromkeys() method

We can use dict.fromkeys() to create a Python dictionary of lists. It is used to create a new dictionary from the collection of keys.

READ:  How to check if a variable is a number in Python?

In the situation where you need to give the same values to every key, then you can use the fromkeys() method of Python.

Syntax

dict.fromkeys(collection_of_keys, val)
  • dict.fromkeys(collection_of_keys, value): The fromkeys() method will work for dictionary only.
  • (collection_of_keys, value): The same value will be assigned to every key which you will give in the first parameter.
keys = ['James', 'Adam', 'John']
values = [88, 79, 84]

emp_data = dict.fromkeys(keys, [])

for key in keys:
    emp_data[key] = values

print(emp_data)
Python dictionary of lists using dict.fromkeys() method

In the above code, we have a list of keys and values, and we need to create the dictionary of lists, so we are using the fromkeys() method, where keys will be given in the first parameter, and the empty list will be assigned to the second parameter like this: emp_data = dict.fromkeys(keys, []).

Then, we use the for loop “for key in keys” to target every element of the keys and assign the same list of values to each key emp_data[key] = values.

Python dict of lists using zip_longest() method

Here, we will use the zip_longest() method of the itertools module. In the previous example, we saw how we can assign the same values to every key, but what if I want different lists of values for every key?

So the zip_longest() method will be helpful to get a different list of values in every different key.

Syntax

zip_longest(" collection_of_keys ", values, fill_value = [])

Here’s an example to create a Python dictionary of lists using the zip_longest() method.

from itertools import zip_longest

keys = ['James', 'Adam', 'John']
values = [
    [72, 63, 87],
    [56, 65, 69],
    [88, 79, 84]
]
emp_data = dict(zip_longest(keys, values, fillvalue=[]))

print(emp_data)
Python dict of lists using zip_longest() method

In the above code, we have a collection of keys and values as nested lists. We need to create a Python dictionary of lists using the zip_longest() method.

So we create a variable named emp_data, using the zip_longest() method and giving keys and values “zip_longest(keys, values, fillvalue=[])” as its parameter, with fill_value = [] as an optional parameter. Finally, we convert it into the dictionary “dict(zip_longest(keys, values, fillvalue=[]))” using the dict() method of Python.

Create a Python dictionary of lists using subscript

Here, we will show you the easiest way to create a Python Dictionary of lists by directly assigning the list to the dictionary keys.

Syntax

myDict["key"] = ["val_1 ", "val_2",. . . .]

Let’s understand with the example,

user_data = {}

user_data["username_1"] = ["abc@gmail.com ", "1234", 42]
user_data["username_2"] = ["xyz@gmail.com", "7894", 56] 

print(user_data)
Create Python dictionary of lists using subscript

In the above code, we created an empty dictionary named user_data and then assigned the list to the dictionary, with the key as the username and the other data like email, password, and age as a list like this: user_data[“username_1”] = [“abc@gmail.com “, “1234”, 42].

Conclusion

In this Python article, you learned how to create a dictionary of lists in Python using 9 different methods and techniques, such as the defaultdict() method, the for loop, and the update() method.

We’ve also explained the scenario so you’ll understand where you should use all these methods and approaches in Python.