Here are eight ways to initialize a dictionary in Python:
- Using literals
- Using dict() Constructor
- Using fromKeys()
- Using Dictionary Comprehensions
- Using zip() and dict Constructor
- Using tuple
- Using setdefault()
- Using __setitem__()
Method 1: Using literals
This is the easiest way to initialize a dictionary with key-value pairs as literals enclosed in curly braces.
Visual Representation
Example
# Initializing an empty dictionary
empty_dict = {}
print(empty_dict)
# Dictionary with initial key-value pairs
my_dict = {
"India": "Delhi",
"USA": "Washington, D.C.",
"France": "Paris",
"Japan": "Tokyo"
}
print(my_dict)
Output
{}
{'India': 'Delhi', 'USA': 'Washington, D.C.', 'France': 'Paris', 'Japan': 'Tokyo'}
Method 2: Using dict() Constructor
This method can be utilized with keyword arguments, where each argument represents a key-value pair in the dictionary.
Example
my_dict = dict(India="Delhi", USA="Washington, D.C.",
France="Paris", Japan="Tokyo")
print(my_dict)
Output
{'India': 'Delhi', 'USA': 'Washington, D.C.', 'France': 'Paris', 'Japan': 'Tokyo'}
Method 3: Using fromkeys()
The fromKeys() method creates a new dictionary with keys from a given iterable, assigning the same shared value to all keys.
Visual Representation
Example
keys = {'Trump', 'Modi', 'Putin'}
value = 'Politician'
my_dict = dict.fromkeys(keys, value)
print(my_dict)
Output
{'Trump': 'Politician', 'Putin': 'Politician', 'Modi': 'Politician'}
Method 4: Using Dictionary Comprehensions
Dictionary comprehensions is particularly useful when you want to create a dictionary dynamically based on some logic or operation on an iterable.
Visual Representation
Example
# Creating a dictionary with keys as numbers and values as their squares
my_dict = {x: x**2 for x in range(5)}
print(my_dict)
Output
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
Method 5: Using zip() and dict Constructor
The zip function pairs elements from the keys and values lists.
The dict constructor then takes these key-value pair and constructs a dictionary from them.
Example
keys = ['India', 'USA', 'France', 'Japan']
values = ['Delhi', 'Washington, D.C.', 'Paris', 'Tokyo']
my_dict = dict(zip(keys, values))
print(my_dict)
Output
{'India': 'Delhi', 'USA': 'Washington, D.C.', 'France': 'Paris', 'Japan': 'Tokyo'}
Method 6: Using tuple
You can also pass values to the dict() constructor using a list of tuples, with each tuple representing a key-value pair.
Example
my_dict = dict([('India', 'Delhi'), ('USA', 'Washington, D.C.'),
('France', 'Paris'), ('Japan', 'Tokyo')])
print(my_dict)
Output
{'India': 'Delhi', 'USA': 'Washington, D.C.', 'France': 'Paris', 'Japan': 'Tokyo'}
Method 7: Using setdefault()
If you have a set of keys and you want to ensure they exist in the dictionary with default values, you can use setdefault().
Example
keys = ['India', 'USA', 'France', 'Japan']
default_value = None
my_dict = {}
for key in keys:
my_dict.setdefault(key, default_value)
print(my_dict)
Output
{'India': None, 'USA': None, 'France': None, 'Japan': None}
Method 8: Using __setitem__()
Although it is not conventional way but you can directly call __setitem__() on a dictionary instance to set its key-value pairs.
my_dict = {}
my_dict.__setitem__('India', 'Delhi')
my_dict.__setitem__('USA', 'Washington, D.C.')
my_dict.__setitem__('France', 'Paris')
my_dict.__setitem__('Japan', 'Tokyo')
print(my_dict)
Output
{'India': 'Delhi', 'USA': 'Washington, D.C.', 'France': 'Paris', 'Japan': 'Tokyo'}
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.