![]() |
VOOZH | about |
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.
This method involves manually defining a dictionary where each key is explicitly assigned a list of values.
Example:
{'1': [1, 2], '2': ['Geeks', 'For', 'Geeks']}
Explanation:
Let's look at other methods of creating a dictionary of lists:
Table of Content
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:
{'Fruits': ['Apple', 'Banana'], 'Vegetables': ['Carrot', 'Spinach'], 'Drinks': ['Water', 'Juice']}
Explanation:
defaultdict automatically creates a default value for keys that don’t exist, making it ideal for building a dictionary of lists dynamically.
Example:
defaultdict(<class 'list'>, {1: ['Apple'], 2: ['Banana'], 3: ['Carrot']})
Explanation:
setdefault() method simplifies handling missing keys by initializing a default list if the key doesn’t exist.
Example:
{'Fruits': ['Apple', 'Banana'], 'Vegetables': ['Carrot']}
Explanation:
Dictionary comprehension is a concise way to create a dictionary of lists from structured data.
Example:
{'Fruits': ['Apple', 'Banana'], 'Vegetables': ['Carrot']}
Explanation: