Initializing a Python dictionary
Python dictionaries are ordered and mutable. Dictionaries do not allow duplicate entries to be stored.
In Python 3.6 and below, dictionaries used to be unordered. After the introduction of Python 3.7+, dictionaries are sorted.
This tutorial will discuss different ways to initialize dictionaries in Python.
Initializing a dictionary in Python using literal syntax
{}
Dictionaries are created and initialized
using curly braces , which contain keys and values.
The following code initializes a Python dictionary using a literal.
dict1 = {"X": 2, "Y": 3, "Z": 4}
print(dict1)
Output:
{'X': 2, 'Y': 3, 'Z': 4}
Initializing a Python dictionary using dict()
the constructor
dict()
The constructor can be used to initialize a dictionary from keyword arguments, a separate dictionary and its keyword arguments, or a separate iterable of key-value pairs.
We can dict()
pass arguments in the constructor and create a dictionary.
The following code uses dict()
the constructor to initialize a dictionary in Python.
dict1 = dict(X=1, Y=2, Z=3)
print(dict1)
Output:
{'X': 1, 'Y': 2, 'Z': 3}
fromkeys()
Initialize a Python dictionary
using the
If all keys have the same value, you can use fromkeys()
the function.
The following code uses fromkeys()
the method to initialize a Python dictionary.
dict1 = dict.fromkeys(["X", "Y", "Z"], 0)
print(dict1)
Output:
{'X': 0, 'Y': 0, 'Z': 0}
If no specific value is specified in the syntax, the dictionary is initialized with values for all keys None
.
dict1 = dict.fromkeys(["X", "Y", "Z"])
print(dict1)
Output:
{'X': None, 'Y': None, 'Z': None}
Initializing a Python dictionary using a list of tuples
Lists of tuples can also be used to initialize dictionaries in Python. This method also uses dict()
the constructor to achieve this.
A tuple is an ordered and immutable collection of objects. It can be used to store multiple items in a single variable.
Lists are similar to tuples, the only difference is that lists can be changed, while tuples do not allow this.
The following code initializes a dictionary in Python using a list of tuples.
LOT = [("X", 5), ("Y", 6), ("Z", 8)]
dict1 = dict(LOT)
print(dict1)
Output:
{'X': 5, 'Y': 6, 'Z': 8}
Initializing a Python dictionary using two lists
In this case, we declare two lists where the values of the first list are used as keys and the second list is used as the values of the dictionary we are going to initialize.
To implement the above statement, we can use zip()
the function, which iterates over two given lists in parallel.
zip()
The function will create a key-value pair for all entries in parallel and will successfully create a compressed object which can then be passed to dict()
the constructor to create a dictionary.
The following code uses two lists to initialize a dictionary in Python.
if __name__ == "__main__":
L1 = ["X", "Y", "Z"]
L2 = [5, 6, 8]
dict1 = dict(zip(L1, L2))
print(dict1)
Output:
{'X': 5, 'Y': 6, 'Z': 8}
In this case, L1 is the list used as keys and L2 is the list used as values for the initialized dictionary.
For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.
Related Articles
Writing logs to a file in Python
Publish Date:2025/05/06 Views:132 Category:Python
-
This tutorial will show you how to write logs to files in Python. Use the module in Python logging to write logs to files Logging is used to debug a program and find out what went wrong. logging The log module is used to log data to a file
Comparing two dates in Python
Publish Date:2025/05/06 Views:97 Category:Python
-
This tutorial explains how to compare two dates in Python. There are multiple ways to determine which date is greater, so the tutorial also lists different sample codes to illustrate the different methods. Comparing two dates in Python usin
Reload or unimport modules in Python
Publish Date:2025/05/06 Views:58 Category:Python
-
Modules allow us to store definitions of different functions and classes in Python files, which can then be used in other files. pandas , NumPy , scipy , Matplotlib are the most widely used modules in Python. We can also create our own modu
Pausing program execution in Python
Publish Date:2025/05/06 Views:156 Category:Python
-
This tutorial will demonstrate various ways to pause a program in Python. Pausing the execution of a program or application is used in different scenarios, such as when a program requires user input. We may also need to pause the program fo
Importing modules from a subdirectory in Python
Publish Date:2025/05/06 Views:190 Category:Python
-
This tutorial will explain various ways to import modules from subdirectories in Python. Suppose we have a file in a subdirectory of our project directory and we want to import this file and use its methods in our code. We can import files
Sleeping for a number of milliseconds in Python
Publish Date:2025/05/06 Views:124 Category:Python
-
In this tutorial, we will look at various ways to pause or suspend the execution of a program in Python for a given amount of time. Let's say we want to pause the execution of a program for a few seconds to let the user read instructions ab
Python Numpy.pad Function
Publish Date:2025/05/06 Views:104 Category:Python
-
In Python, we have NumPy the array module to create and use arrays. Arrays can have different sizes and dimensions. Padding is a useful method that can be used to compensate for the size of an array. We can mutate an array and add some padd
Generating Random Colors in Python
Publish Date:2025/05/06 Views:135 Category:Python
-
In the digital world, colors are represented in different formats. RGB, Hexadecimal format are just some of the commonly used formats. In this tutorial, we will learn how to generate random colors in Python. When we talk about generating ra
Getting the name of a class in Python
Publish Date:2025/05/06 Views:83 Category:Python
-
Just like object constructors, classes can be defined as user-defined prototypes for creating objects. class Classes can be created using the keyword . A class is a data structure that can contain both data members and member methods. This