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 example, given two lists, keys = ['a', 'b', 'c'] and values = [1, 2, 3], the goal is to construct a dictionary like {'a': 1, 'b': 2, 'c': 3}, mapping each key to its corresponding value.
Using dict()
dict() constructor provides a simple and direct way to create dictionaries using keyword arguments. This method is useful for defining static key-value pairs in a clean and readable manner.
d = dict(a=1, b=2, c=3)
print(d)
Output
{'a': 1, 'b': 2, 'c': 3}
Explanation: dict() creates a dictionary by directly assigning key-value pairs as keyword arguments.
Table of Content
Using dictionary comprehension
Dictionary comprehension is a efficient way to create a dictionary from iterable sequences like lists or tuples. It allows mapping keys to values using a single line of code, making it highly readable and optimal for small to medium datasets.
keys = ['a', 'b', 'c']
values = [1, 2, 3]
d = {k: v for k, v in zip(keys, values)}
print(d)
Output
{'a': 1, 'b': 2, 'c': 3}
Explanation:{k: v for k, v in zip(keys, values)} iterates over key-value pairs generated by zip(), assigning each key to its respective value and constructing the dictionary d .
Using defaultdict
defaultdict is a powerful tool that automatically initializes missing keys with a default value. It is particularly useful for grouping multiple values under the same key without explicit key existence checks.
from collections import defaultdict
a = [('a', 1), ('b', 2), ('a', 3), ('c', 4)]
d = defaultdict(list) # Create a defaultdict with list as the default value type
for key, value in a:
d[key].append(value)
print(dict(d))
Output
{'a': [1, 3], 'b': [2], 'c': [4]}
Explanation: for loop iterates through the list a , appending values directly, eliminating the need for key existence checks. Finally, the defaultdict is converted to a regular dictionary.
Using setdefault()
setdefault() method simplifies dictionary creation by initializing keys with a default value if they don’t already exist. This approach is helpful when handling dynamic data where keys may appear multiple times.
a = [('a', 1), ('b', 2), ('a', 3), ('c', 4)]
d = {}
for key, val in a:
d.setdefault(key, []).append(val)
print(d)
Output
{'a': [1, 3], 'b': [2], 'c': [4]}
Explanation:for loop extracts key and val from each tuple in a. setdefault(key, []) initializes an empty list for new keys, preventing errors and .append(val) then adds values, efficiently grouping multiple entries under the same key.
Using for loop
A traditional for loop can be used to create a dictionary by iterating over two lists or handling dynamic key-value assignments. This method is useful when additional operations or transformations are required before storing the data.
keys = ['p', 'q', 'r']
values = [5, 10, 15]
d = {}
for i in range(len(keys)):
d[keys[i]] = values[i]
print(d)
Output
{'p': 5, 'q': 10, 'r': 15}
Explanation: for loop iterates through the keys list using an index-based loop. Each key from keys is mapped to its corresponding value from values using d[keys[i]] = values[i].