Python

10 most useful Python Dictionary Methods

10 most useful Python Dictionary Methods
Dictionary is used in python to store multiple data with key-value pairs. It works like an associative array of other programming languages. The curly () brackets are used to define a dictionary and the key-value is defined by the colon(:). The content of the key and value can be numeric or string. Python has many built-in methods to do different types of tasks on the dictionary data such as add, update, delete, search, count, etc. 10 most useful dictionary methods of python are explained in this article.

Use of items() method

items() method is used to return a list with the tuple pairs of all keys and values of a dictionary.

Syntax:

dictionary.items()

This method does not take any argument.

Example:

A dictionary variable named products is declared in the script. The keys contain the product name and the value contains the price of the product. Next, items() method is used for the dictionary and stored into another variable named itemlist and it is printed later.

#!/usr/bin/env python3
# Define a dictionary
products = 'Fresh Oil': 500, 'Mango Juice': 30, '5 star Chocalate': 20,
'Dan Fruit Cake':50
# Store the return value of the item() method
itemlist = products.items()
# Print the output of item() method
print('The output of items() method:\n', itemlist)

Output:

The following output will appear after running the script from spyder.

Use of keys() method

keys() method is used to return a list of all keys of a dictionary.

Syntax:

dictionary.keys()

This method does not take any argument.

Example:

A dictionary variable named products is declared in the script. The keys contain the product name and the value contains the price of the product like the previous example. keys() method is applied in the dictionary and the return values are stored in the variable named keylist that is printed later. If you want the list of all values of the dictionary then you have to use values() method.

#!/usr/bin/env python3
# Define a dictionary
products = 'Fresh Oil': 500, 'Mango Juice': 30, '5 star Chocalate': 20,
'Dan Fruit Cake':50
# Store the return value of the keys() method
keylist = products.keys()
# Print the output of keys() method
print('The output of keys() method:\n', keylist)

Output:

The following output will appear after running the script from spyder.

Use of setdefault() method

setdefault() method is used to get the value of any particular key from a dictionary if the key exists. This method can be used to set a default value if the specified key does not exist in the dictionary.

Syntax:

dictionary.setdefault(key_value [, default_value])

This method has two arguments. The first argument is mandatory and it is used to take the key value that will be searched in the dictionary. The second argument is optional and it is used to set a default value if the key used in the first argument does not exist in the dictionary. If the key does not exist in the dictionary and the default value is not defined then this method will return 'none'.

Example:

The following script shows the use of the setdefault() method in the dictionary. The dictionary named products is declared in the script like previous examples. Here, the setdefault() method is used with one argument for the first time and stored into the variable named  juice_price. The method is used with two arguments for the second time and stored into the variable named cake_price. Both variables are printed later.

#!/usr/bin/env python3
# Define a dictionary
products = 'Fresh Oil': 500, 'Mango Juice': 30, '5 star Chocolate': 20,
'Dan Fruit Cake':50
# Read the value of a key that exists in the dictionary
juice_price = products.setdefault('Mango Juice')
# Print the value
print('Juice price is TK.',juice_price)
# Read the value of a key that does not exists in the dictionary
cake_price = products.setdefault('Cake',35)
# Print the value
print('Cake price is TK.',cake_price)

Output:

The following output will appear after running the script from spyder. The key, 'Mango Juice' exists in the dictionary and the value of this key is 30 that is printed. The key, 'Cake' does not exist in the dictionary. So, the default value of the setdefault() method, 35 is printed.

Use of get() method

get() method works similar to setdefault() method but there is one difference between these methods. Two arguments are mandatory in the get() method and the second argument is optional in the setdefault() method.

Syntax:

dictionary.get(key_value , default_value)

It will return the corresponding value from the dictionary which key matches the first argument of this method otherwise it will return the default value that is assigned in the second argument.

Example:

The same dictionary variable of the previous example is used in the following script. Here, get() method is used for two times with two different key values. The return values of this method are printed later.

#!/usr/bin/env python3
# Define a dictionary
products = 'Fresh Oil': 500, 'Mango Juice': 30, '5 star Chocolate': 20,
'Dan Fruit Cake':50
# Read the value of a key that does not exist in the dictionary
choc_price = products.get('Chocolate',15)
# Print the value
print('Chocolate price is TK.',choc_price)
# Read the value of a key that exists in the dictionary
juice_price = products.get('Mango Juice',15)
# Print the value
print('Juice price is TK.',juice_price)

Output:

The following output will appear after running the script from spyder. The first key used in get() method is 'Chocolate' that does not exist in the dictionary. So the default value is returned and printed. The second key value used in the get() method is 'Mango Juice' that exists in the dictionary and the corresponding value of that key is returned from the dictionary and printed.

Use of len() method

len() method is used to count the total number of elements in the dictionary.

Syntax:

len(dictionary)

It takes a dictionary variable as an argument and returns the total numbers of elements of that dictionary.

Example:

The following script counts the total elements of the dictionary named products and the returned value is printed.

#!/usr/bin/env python3
# Define a dictionary
products = 'Fresh Oil': 500, 'Mango Juice': 30, '5 star Chocolate': 20,
'Dan Fruit Cake':50
# Count the total elements of the dictionary
print("Total items of the dictionary are:", len(products))

Output:

The following output will appear after running the script from spyder. 4 elements in the dictionary are printed in the output.

Use of pop() method

The pop() method is used to retrieve the particular value and remove the element from a dictionary based on the key value.

Syntax:

dictionary.pop(key [, value])

This method has two arguments. The first argument is mandatory which is used to take the key value. The second argument is optional and it is used to set the default value that will be returned if the key assigned in the first argument does not exist in the dictionary.

Example:

A dictionary variable named dictvar is declared in the following script that contains four elements. The pop() method is used for two times in the script with two different key values. In the first pop() method, 'Phone' is used as key and no optional value is used. In the second pop() method, the same key value is used with an optional value. The two returned values of this method are printed later.

#!/usr/bin/env python3
# Define a dictionary
dictvar = 'Name': 'Sakib Al Hasan', 'Profession': 'Cricketer','Phone':'01866564234',
'Salary':300000 print("\nThe content of the dictionary:\n",dictvar)
# Read and delete a value from the dictionary if exists
print("\nThe phone no is:", dictvar.pop('Phone'))
# Print the dictionary after pop
print("\nThe content of the dictionary after pop:\n",dictvar)
# Read a key of the dictionary that does not exist
print("\nThe phone no is:", dictvar.pop('Phone','01766345234'))

Output:

The following output will appear after running the script from spyder. The key, 'Phone' exists in the dictionary. So, when the pop() method is used for the first time then the corresponding value of the 'Phone' key is returned from the dictionary and this element is removed from the dictionary. Next time, when the pop() method is used with the same key value then it does not exist in the dictionary, and the optional value of the pop() method is returned.

Use of update() method

update() method is used between two dictionaries.  If any key of the second dictionary matches with any key of the first dictionary then the corresponding value of the first dictionary will be updated by the corresponding value of the second dictionary. The keys of the second dictionary that do not match with any key of the first dictionary those elements of the second dictionary are added at the end of the first dictionary.

Syntax:

dictionary1.update(dictionary2)

It takes dictionary2 as an argument that will be used to update the dictionary1.

Example:

Two dictionaries, dict1 and dict2 are declared in the following script. dict2 used to update dict1 by using update() method. The dict1 is printed before and after using the update() method.

#!/usr/bin/env python3
# Define two dictionaries
dict1 = '01117856': 2.97, '01113456': 3.69, '01118734': 3.89
dict2 = '01113456': 3.33, '011113423': 3.98
# Print the dict1
print("The content of the first dictionary before update:\n", dict1)
# Update dict1 by dict2
dict1.update(dict2)
# Print the dict1 after update
print("The content of the first dictionary after update:\n", dict1)

Output:

The following output will appear after running the script from spyder. Here, one key is common in both dict1 and dict2, which is '01113456'. So the value of this key in dict1 is updated by the value of dict2. Another key of dict2 does not exist in dict1 and this element is added at the end of dict1.

Use of copy() method

copy() method is used to make a copy of a dictionary. It is useful when we need to store the original copy of a dictionary before modification.

Syntax:

dictionary1.copy()

This method does not take any argument.

Example:

In the following script, the dict1 is copied to dict2. Both variables use different memory. So, if you change any value of one dictionary then it will not create any change on another copy of the dictionary. Here, one value of dict2 is changed and both dictionaries are printed later.

#!/usr/bin/env python3
# Define a dictionary
dict1 = '01117856': 2.97, '01113456': 3.69, '01118734': 3.89
# Create a copy of the dictionary
dict2 = dict1.copy()
# Update a value of the key of the copied dictionary
dict2['01118734'] = 3.99
# Print the original dictionary
print("The content of the original dictionary:\n", dict1)
# Print the copied dictionary
print("The content of the copied dictionary:\n", dict2)

Output:

The following output will appear after running the script from spyder. The output shows that the changes in dict2 do not create any change in dict1.

Use of sorted() method

sorted() method is used in the dictionary to sort the key values only

Syntax:

sorted(dictionary)

It takes any dictionary variable as an argument and returns the sorted keys of the dictionary.

Example:

A dictionary named dictvar is declared in the following script. Next, the sorted() method is used to sort the keys of the dictionary and stored in the variable named sorted_key. The values of this variable are printed later.

#!/usr/bin/env python3
# Define a dictionary
dictvar = 567: 3.97, 345: 2.69, 745: 3.89
# Sort the keys of the dictionary
sorted_key = sorted(dictvar)
# Print the sorted keys
print("The content of the sorted key:\n", sorted_key)

Output:

The following output will appear after running the script from spyder.

Use of clear() method

The clear() method is used to remove all elements of a dictionary.

Syntax:

dictionary.clear()

This method does not take any argument. and it returns an empty dictionary.

Example:

A dictionary variable named dictvar is declared in the following script like before and a clear() method is applied to this dictionary. The dictionary is printed before and after using the clear() method.

#!/usr/bin/env python3
# Define a dictionary
dictvar = 1001: 3.97, 1002: 2.69, 1003: 3.89
# Print the content of the dictionary
print("The content of the dictionary:\n", dictvar)
# Remove all items of the dictionary
dictvar.clear()
# Print the dictionary after clear
print("The content of the dictionary:\n", dictvar)

Output:

The following output will appear after running the script from spyder.

Conclusion:

The 10 most useful dictionary methods of python are described in this article by using very simple examples. This will help the python users to work more efficiently with the dictionary data.

Безкоштовні ігри з відкритим кодом для розробки ігор Linux
У цій статті буде розглянуто перелік безкоштовних ігрових механізмів з відкритим кодом, які можна використовувати для розробки 2D та 3D ігор на Linux....
Підручник Тінь розкрадача гробниць для Linux
Shadow of the Tomb Raider - дванадцяте доповнення до серії Tomb Raider - франшизи екшн-пригодницької гри, створеної Eidos Montreal. Гру сприйняли як к...
Як збільшити FPS в Linux?
FPS означає Кадри в секунду. Завданням FPS є вимірювання частоти кадрів при відтворенні відео або ігрових виставах. Простими словами кількість безпере...