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
Initialize a Dictionary with Custom Value list in Python
Initializing a dictionary with custom value lists means creating a dictionary where each key maps to a list containing specific values. This approach is useful when you need to group multiple values under each key or when you want each value to be in list format for further manipulation.
Syntax Overview
Python provides several built-in functions to initialize dictionaries with custom value lists:
- range() - Returns a sequence of numbers
- len() - Returns the length of an object
- zip() - Combines multiple iterables
- dict() - Creates a dictionary
- enumerate() - Iterates with index tracking
Using for Loop
The most straightforward approach uses a for loop to iterate through keys and values, wrapping each value in a list ?
keys = ['P', 'Q', 'R', 'S', 'T']
values = [11, 92, 53, 94, 67]
result = {}
for i in range(len(keys)):
result[keys[i]] = [values[i]]
print("Dictionary with custom value list:")
print(result)
Dictionary with custom value list:
{'P': [11], 'Q': [92], 'R': [53], 'S': [94], 'T': [67]}
Using zip() Function
The zip() function combined with dict() provides a more concise solution ?
keys = ['M', 'N', 'O']
values = [100, 200, 300]
result = dict(zip(keys, [[value] for value in values]))
print("Dictionary using zip():")
print(result)
Dictionary using zip():
{'M': [100], 'N': [200], 'O': [300]}
Using Dictionary Comprehension
Dictionary comprehension offers the most Pythonic and readable approach ?
subjects = ['Math', 'English', 'Hindi', 'Science']
scores = [95, 78, 82, 65]
result = {subjects[i]: [scores[i]] for i in range(len(subjects))}
print("Subject with scores:")
print(result)
Subject with scores:
{'Math': [95], 'English': [78], 'Hindi': [82], 'Science': [65]}
Using enumerate() with zip()
When you need index tracking, combine enumerate() with zip() ?
names = ['John', 'Mark', 'Jonathan', 'Sam', 'Karl']
ages = [18, 26, 22, 24, 33]
result = {name: [age] for i, (name, age) in enumerate(zip(names, ages))}
print("Person name with age:")
print(result)
Person name with age:
{'John': [18], 'Mark': [26], 'Jonathan': [22], 'Sam': [24], 'Karl': [33]}
Comparison of Methods
| Method | Readability | Performance | Best For |
|---|---|---|---|
| For Loop | Good | Moderate | Beginners, complex logic |
| zip() + dict() | Good | Fast | Simple key-value mapping |
| Dictionary Comprehension | Excellent | Fast | Most scenarios |
| enumerate() + zip() | Good | Fast | When index is needed |
Conclusion
Dictionary comprehension is the most Pythonic approach for initializing dictionaries with custom value lists. Use zip() for simple mappings, for loops when you need complex logic, and enumerate() when tracking indices is important.
