. Advertisement .
..3..
. Advertisement .
..4..
There are more ways to initialize a dictionary in Python. Having a firm grasp of them will improve your programming skills and make your code more flexible and elegant. Check out what these options are and when you can use them.
How To Initialize A Dictionary In Python
Using Curly Braces {}
Curly braces {} are the easiest way to create a dictionary. A simple pair without anything in it generates an empty dictionary.
Example:
empty = {}
print(empty)
#{}
You can add items during initialization by putting key: value pairs separated by commas between the braces.
Syntax:
dictionary_name = {key1: value1, key2: value2, ..., key_n: value_n}
Example:
Code:
car1 = {"Brand":"Audi","Series":"A7 2021","Fuel type":"Gasoline"}
print(car1)
output:
{'Brand': 'Audi', 'Series': 'A7 2021', 'Fuel type': 'Gasoline'}
You can access the values of items in the dictionary through their associated keys by using the square brackets or the get() method:
Code:
print(car1['Brand'])
print(car1.get('Series'))
Audi
A7 2021
You can provide values of any type that can be duplicated. However, the keys of a dictionary must be unique and belong to an immutable type (number, string, or tuple).
Using The dict() Constructor
The dict() type constructor allows you to directly build a dictionary from a sequence of key-value pairs.
Example:
Code:
car2 = dict({"Brand":"Volkswagen",
"Series":"Tiguan Luxury S",
"Drive system":"FWD"})
print(car2)
Output:
{'Brand': 'Volkswagen', 'Series': 'Tiguan Luxury S', 'Drive system': 'FWD'}
Other ways to initialize a dictionary in Python with dict():
car3 = dict([('Brand','BMW'),('Series','X7 2022'),('Drive system','Fulltime 4WD')])
print(car3) # {'Brand': 'BMW', 'Series': 'X7 2022', 'Drive system': 'Fulltime 4WD'}
fruits = dict(Aplle=12, Mango=9, Cherry=25)
print(fruits) # {'Aplle': 12, 'Mango': 9, 'Cherry': 25}
If you pass no arguments, dict() creates an empty dictionary:
empty_dict = dict()
print(empty_dict)
#{}
Using fromkeys()
The fromkeys() method of the dict class can help you create a dictionary with a predefined set of keys and, sometimes, values.
Syntax:
dict.fromkeys(keys, value)
In the statement, keys are required, and value is optional. The method will give every key the None value in the absence of the value argument.
Example:
Code:
countries = ['Portugal', 'Hungary', 'England']
continental = 'Europe'
dictionary1 = dict.fromkeys(countries)
dictionary2 = dict.fromkeys(countries, continental)
print(dictionary1)
print(dictionary2)
Output:
{'Portugal': None, 'Hungary': None, 'England': None}
{'Portugal': 'Europe', 'Hungary': 'Europe', 'England': 'Europe'}
Using zip()
Using zip() and dict() in conjunction is a convenient method to initialize a dictionary in Python from two closely related sequences.
Example:
Code:
fields = ['Name', 'Continental', 'Currency unit']
country1 = ['England', 'Europe', 'GBP']
country2 = ['USA', 'America', 'USD']
country3 = ['Russia', 'Europe', 'RUB']
dictionary1 = dict(zip(fields, country1))
dictionary2 = dict(zip(fields, country2))
dictionary3 = dict(zip(fields, country3))
print(dictionary1)
print(dictionary2)
print(dictionary3)
Output:
{'Name': 'England', 'Continental': 'Europe', 'Currency unit': 'GBP'}
{'Name': 'USA', 'Continental': 'America', 'Currency unit': 'USD'}
{'Name': 'Russia', 'Continental': 'Europe', 'Currency unit': 'RUB'}
Each time it is called in the snippet above, the zip() function aggregates two lists into a tuple, from which the dict() function generates a dictionary.
You can see the content of those tuples:
print(list(zip(fields, country1))) #[('Name', 'England'), ('Continental', 'Europe'), ('Currency unit', 'GBP')]
print(list(zip(fields, country2))) # [('Name', 'USA'), ('Continental', 'America'), ('Currency unit', 'USD')]
print(list(zip(fields, country3))) #[('Name', 'Russia'), ('Continental', 'Europe'), ('Currency unit', 'RUB')]
Using Dictionary Comprehension
Dictionary comprehension is an advanced way to initialize a dictionary in Python. But if you can master it, it can make your code more concise and elegant.
Examples with dictionary comprehension:
Code:
# Method 1
shape = {a: a*a for a in range(5)}
print(shape)
# Method 2
dictionary1 = {'a': 11, 'b': 22, 'c': 33, 'd': 44, 'e': 55}
dictionary2 = {i:j*j for (i,j) in dictionary1.items()}
print(dictionary2)
Output:
# Method 1
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
# Method 2
{'a': 121, 'b': 484, 'c': 1089, 'd': 1936, 'e': 3025}
Conclusion
There is no one-size-fits-all way to initialize a dictionary in Python. The more solutions you master, the more efficient your program can be.
Leave a comment