Python dictionary is one of the most popular data structures which hold data in key-value pairs. So to use the dictionary, users first create a dictionary, access the elements, and change the attributes based on the requirements of the programmers.
Unlike other Python data structures, the dictionary is the only data structure that does not contain singular items as the objects. A dictionary contains key-value pairs, improving the efficiency of the Python data structures.
The article will use different approaches to create an empty dictionary and a dictionary with elements in key-value pairs. Also, this Python article will briefly highlight the keys and values of a dictionary.
Creating a dictionary in Python
Users can create a dictionary in Python by inserting a group of data as objects inside the curly braces and dividing each object with a "comma." Using this data structure, users can keep track of multiple entries, one with the keys and the others with values of the keys, and together referred to as key-value pairs.
The main difference between the keys and the values is that users can keep objects of any data type as the values for the keys and is mutable. But the keys take only those objects of data types which are immutable and unique, such as integers, floats, string, Boolean, etc.
Create an empty dictionary in Python
Before creating an empty dictionary in Python, users first initialize a variable that will be the dictionary name. Here is an example of how to create an empty
Code:
dictionary = {}
print(dictionary)
print(type(dictionary))
Output:
Again, we can also create an empty dictionary using the dict() method of Python. It is a built-in method in Python that generates a dictionary of the user's choice simply without passing arguments:
dictionary = dict()
print(dictionary)
print(type(dictionary))
Output:
Create a dictionary with data elements
Users can use the key-value pairs to insert data elements as objects inside the curly brackets in the Python dictionary while creating it. Users first initialize a variable that will define the dictionary.
Then, the "equals to" operator assigns the key-value pair to the variable. Users declare the dictionary using curly brackets and separate the key and the associated value with a colon ":"
Syntax:
dictionary = {key: value}
Code Snippet:
dictionary = {"Emp_name": "Shamy", "Age": 27, "Company": "Google"}
print(dictionary)
print(type(dictionary))
Output:
Explanation:
We used curly brackets and added three key-value pairs that define random information about an employee. We used the variable "dictionary" that stores the data elements, which are "Emp_name": "Shamy," "Age": 27, "Company": "Google." Here, the keys are "Emp_name," "Age," and "Company," and the values are "Shamy," 27 and "Google, respectively." When users declare a dictionary with multiple key-value pairs, they use a comma as the separator within each key-value.
Create a dictionary with items using the dict() method
As we have seen above, using the built-in method dict(), users create an empty dictionary. Similarly, the method can also create a dictionary with key-value pairs having data elements. If users pass arguments in the dict() method, it will create a dictionary with keys and values based on the requirements.
Code Snippet:
dictionary = dict({"Emp_name": "Shamy", "Age": 27, "Company": "Google"})
print(dictionary)
print(type(dictionary))
Output:
Explanation:
We created the dictionary using the dict() method and passed the key-value pairs as the arguments of the dict() method within curly braces.
Create a dictionary with items using the fromkeys() method
Again, another efficient way to generate a Python dictionary is through the fromkeys() method. It returns the keys and values that users specify as the arguments.
Syntax:
dictionary_name = dict.fromkeys(sequence,value)
Code Snippet:
demo = ("Emp_name", "Age", "Company")
dictionary = dict.fromkeys(demo)
print(dictionary)
Output:
Explanation:
We used the fromkeys() method and passed the argument with the keys of the Python dictionary. As we can see, in the output, all the values are "None" because we have passed only one item, i.e., dictionary keys, as the argument.
Last example of the fromkeys() method is as follows:
Code:
demo1 = ("India", "Dubai", "Japan")
demo2 = "Asia"
dictionary = dict.fromkeys(demo1, demo2)
print(dictionary)
Output:
Explanation:
In this example, we passed the keys in one variable "demo1," and values in another variable "demo2." Then, the fromkeys() method inserts the value to each key, which creates a dictionary with respective key-value pairs.
Adding and Removing Elements in Dictionary
Adding and removing objects is a part of creating a new dictionary in Python. There are simple Python functions and methods; which will insert elements according to the user's input.
Code Snippet:
dict = {}
print("We created an empty dictionary: ")
print(dict)
dict[1.0] = 'Hello'
dict[2.0] = 'Python'
dict.update({ 3.0 : 'Dictionary'})
print("\n We created a dictionary after adding the new item: ")
print(dict)
dict['my_list'] = 0, 1, 2
print("\n We created a dictionary after adding the list: ")
print(dict)
dict[2] = 'Example'
print("\n We updated the dictionary: ")
print(dict)
dict[4.0] = {'Nestedkey' :{1.00 : 'Nested', 2.00 : 'Key'}}
print("\n We added the Nested Key to create a new dictionary: ")
print(dict)
Output:
Explanation:
In the above example, we created five different dictionaries with different scenarios. The first dictionary is an empty dictionary. The second specifies a dictionary after adding one item with the key "3.0". In the third, we added a list and created another dictionary. The last creates a new dictionary with nested keys.
Users can remove data elements from the dictionary using the Python built-in pop() and clear() methods. The following code is an example of removing elements from the dictionary:
Code:
dict = {1.0: "A", 2.0: "B", 3.0: "C", 4.0: "D", 5.0: "E"}
dict.pop(3.0)
print("\n We removed the third item from the dictionary and the new dictionary is: ")
print(dict)
dict.popitem()
print("\n We removed an arbitrary key from the dictionary and the new dictionary is: ")
print(dict)
print("\n We removed all the items from the dictionary and created an empty dictionary: ")
dict.clear()
print(dict)
del dict
try:
print(dict)
except:
print('There is no such dictionary of this name')
Output:
Explanation:
The pop() and the clear() methods are the most efficient for removing elements from the dictionary. In the first code, we remove the third element with the key "3.0." The third removes an arbitrary keyed element. And the fourth removes all the elements and creates an empty dictionary.
Conclusion
Coming to the end of this article highlighted different approaches to creating a dictionary, both empty and items with key-value pairs. The Python built-in methods, dict() fromkeys(), can efficiently reduce the code complexities and generate a dictionary with specified keys and values. Without directly creating dictionaries, users can also use the “add and remove” approach that inserts and deletes elements to create a new dictionary in Python.