Ways to create a dictionary of Lists - Python
Last Updated :
07 Jan, 2025
A dictionary of lists is a type of dictionary where each value is a list. These dictionaries are commonly used when we need to associate multiple values with a single key.
Initialize a Dictionary of Lists
This method involves manually defining a dictionary where each key is explicitly assigned a list of values.
Example:
Python
# Creating an empty dictionary
d = {}
# Adding list as value
d["1"] = [1, 2]
d["2"] = ["Geeks", "For", "Geeks"]
print(d)
Output{'1': [1, 2], '2': ['Geeks', 'For', 'Geeks']}
Explanation:
- A dictionary where each key is paired with a list (e.g., [1, 2]).
- This is the most straightforward way to define a dictionary of lists but requires hardcoding all the keys and values.
Let's look at other methods of creating a dictionary of lists:
Using the zip() Function
zip() function can combine two lists (keys and lists of values) into a dictionary of lists. This method is efficient when the data is already structured as two separate lists.
Example:
Python
k = ["Fruits", "Vegetables", "Drinks"]
val = [["Apple", "Banana"], ["Carrot", "Spinach"], ["Water", "Juice"]]
# Create a dictionary of lists using zip
d = dict(zip(k, val))
print(d)
Output{'Fruits': ['Apple', 'Banana'], 'Vegetables': ['Carrot', 'Spinach'], 'Drinks': ['Water', 'Juice']}
Explanation:
- zip(keys, values) combines the keys and values lists into pairs (tuples).
- dict() converts the resulting pairs into a dictionary.
Use defaultdict from collections
defaultdict automatically creates a default value for keys that don’t exist, making it ideal for building a dictionary of lists dynamically.
Example:
Python
from collections import defaultdict
# Initialize a defaultdict with list as the default type
d = defaultdict(list)
# Add values to the dictionary
d[1].append("Apple")
d[2].append("Banana")
d[3].append("Carrot")
print(d)
Outputdefaultdict(<class 'list'>, {1: ['Apple'], 2: ['Banana'], 3: ['Carrot']})
Explanation:
- defaultdict(list) automatically assigns an empty list as the default value for keys that don’t exist.
- append() adds items to the lists associated with the keys. No need to check if the key exists beforehand.
Using setdefault()
setdefault() method simplifies handling missing keys by initializing a default list if the key doesn’t exist.
Example:
Python
li = [("Fruits", "Apple"), ("Fruits", "Banana"), ("Vegetables", "Carrot")]
# Initialize an empty dictionary
d = {}
# Use setdefault to populate the dictionary
for k, item in li:
d.setdefault(k, []).append(item)
print(d)
Output{'Fruits': ['Apple', 'Banana'], 'Vegetables': ['Carrot']}
Explanation:
- setdefault(category, []) checks if the key exists; if not, it creates the key with an empty list as its value.
Using Dictionary Comprehension
Dictionary comprehension is a concise way to create a dictionary of lists from structured data.
Example:
Python
li = [("Fruits", "Apple"), ("Fruits", "Banana"), ("Vegetables", "Carrot")]
# Create dictionary of lists using comprehension
d = {k: [i for _, i in filter(lambda x: x[0] == k, li)] for k in set(k for k, _ in li)}
print(d)
Output{'Fruits': ['Apple', 'Banana'], 'Vegetables': ['Carrot']}
Explanation:
- filter(lambda x: x[0] == k, li) filters items matching the current key.
- Comprehension iterates over unique keys and assigns a list of all matching items as the value.
Similar Reads
How to Create a Dictionary in Python The task of creating a dictionary in Python involves storing key-value pairs in a structured and efficient manner, enabling quick lookups and modifications. A dictionary is an unordered, mutable data structure where each key must be unique and immutable, while values can be of any data type. For exa
3 min read
Convert a list of Tuples into Dictionary - Python Converting a list of tuples into a dictionary involves transforming each tuple, where the first element serves as the key and the second as the corresponding value. For example, given a list of tuples a = [("a", 1), ("b", 2), ("c", 3)], we need to convert it into a dictionary. Since each key-value p
3 min read
Create a List of Tuples in Python The task of creating a list of tuples in Python involves combining or transforming multiple data elements into a sequence of tuples within a list. Tuples are immutable, making them useful when storing fixed pairs or groups of values, while lists offer flexibility for dynamic collections. For example
3 min read
Convert Two Lists into a Dictionary - Python We are given two lists, we need to convert both of the list into dictionary. For example we are given two lists a = ["name", "age", "city"], b = ["Geeks", 30,"Delhi"], we need to convert these two list into a form of dictionary so that the output should be like {'name': 'Geeks', 'age': 30, 'city': '
3 min read
How to Create a List of N-Lists in Python In Python, we can have a list of many different kinds, including strings, numbers, and more. Python also allows us to create a nested list, often known as a two-dimensional list, which is a list within a list. Here we will cover different approaches to creating a list of n-lists in Python. The diffe
3 min read