Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Ways to create a dictionary of lists in python
A dictionary in Python is a collection of data stored in the form of key-value pairs. We can assign different datatypes as the value for a key. Lists store data in sequences that can be traversed and manipulated. When combining these structures, we create a dictionary of lists where lists serve as values for immutable keys.
Basic Understanding
Dictionary Syntax
Dictionaries use curly braces {} ?
car_dict = {"Brand": "AUDI", "Model": "A4"}
print(car_dict)
{'Brand': 'AUDI', 'Model': 'A4'}
List Syntax
Lists use square brackets [] ?
details = ["Name", "age", "gender", "qualification"] print(details)
['Name', 'age', 'gender', 'qualification']
Why Lists Cannot Be Keys
Dictionary keys must be immutable (unchangeable). Lists are mutable, so they cannot serve as keys ?
# This will raise an error
invalid_dict = {["Name", "Age"]: "RAVI"} # TypeError: unhashable type: 'list'
Method 1: Direct Assignment
Create an empty dictionary and assign lists as values to string keys ?
student_data = {}
student_data["Names"] = ["RAM", "RAVI", "TARUN", "MOHAN"]
student_data["Ages"] = [22, 23, 18, 27]
print(student_data)
{'Names': ['RAM', 'RAVI', 'TARUN', 'MOHAN'], 'Ages': [22, 23, 18, 27]}
Method 2: Using defaultdict
The defaultdict automatically creates missing keys with default list values ?
from collections import defaultdict
data_pairs = [("Name", "Arjun"), ("Age", 22), ("Age", 23), ("Age", 28), ("Name", "RAVI"), ("Name", "ADITYA")]
grouped_data = defaultdict(list)
for key, value in data_pairs:
grouped_data[key].append(value)
print(dict(grouped_data))
{'Name': ['Arjun', 'RAVI', 'ADITYA'], 'Age': [22, 23, 28]}
Method 3: Using setdefault()
The setdefault() method returns a key's value or creates the key with a default value if missing ?
range_dict = {}
numbers = [23, 24, 28]
for num in numbers:
for i in range(num, num + 3):
range_dict.setdefault(i, []).append(num)
print(range_dict)
{23: [23], 24: [23, 24], 25: [23, 24], 26: [24], 27: [], 28: [28], 29: [28], 30: [28]}
Method 4: Dictionary Comprehension
Create a dictionary of lists using comprehension for cleaner syntax ?
categories = ["fruits", "colors", "animals"]
items_dict = {category: [] for category in categories}
# Add items to each category
items_dict["fruits"].extend(["apple", "banana", "orange"])
items_dict["colors"].extend(["red", "blue", "green"])
items_dict["animals"].extend(["cat", "dog", "bird"])
print(items_dict)
{'fruits': ['apple', 'banana', 'orange'], 'colors': ['red', 'blue', 'green'], 'animals': ['cat', 'dog', 'bird']}
Comparison
| Method | Best For | Advantage |
|---|---|---|
| Direct Assignment | Simple, known keys | Easy to understand |
defaultdict |
Dynamic key creation | Auto-creates missing keys |
setdefault() |
Conditional key creation | Built-in method |
| Comprehension | Initialization | Clean, readable syntax |
Conclusion
Dictionary of lists is useful for grouping related data. Use defaultdict for dynamic grouping, direct assignment for simple cases, and setdefault() when you need conditional key creation.
