Introduction
A Python Dictionary is a set of key-value pairs with the condition that all the keys within one dictionary should be unique. It is one of the built-in data types among four sequences (list, tuple, set) in Python.
In the dictionary, the collection of items is ordered, and changeable. But in Python 3.6 and earlier versions, dictionaries are unordered means that there is random access of items when using for loop
.
Key in dictionary
Data types supported by keys in dictionaries are all immutable types like strings(str) and numbers(int, float, complex). You can’t use lists, sets as keys, since their values can change at run time.
As a tuple is also an immutable type, you can use it in the condition that it should only contain strings, numbers, or tuples.
Value in dictionary
Values in dictionary items can be of any data type i.e. both mutable and immutable types.
Working with dictionary
Dictionary is used to model various real-world objects. In this tutorial, we will create a simple dictionary object that holds information about the programming language developer. Here key contains the language and its developer as the value associated with the key.
Initializing dictionary
You can initialize the dictionary in two ways: one by curly braces ‘{}’ and another by dict() built-in method.
my_dict = {} # or my_dict = dict()
Check Type
To check the type of variable(references to object) after initializing, use the type() method as:
# checking object type print(type(my_dict))
Output:
<class 'dict'>
Adding new pair
Dictionary supports an unlimited number of key-value pairs. To add a new key-value pair, give the name of the dictionary(assigned variable) followed by the new key in square brackets and assign the new value.
# adding first pair my_dict['C'] = "Dennis Ritchie " # adding second pair my_dict['C++'] = "Bjarne Stroustrup" # adding third pair my_dict['Python'] = "Guido van Rossum" # adding fourth pair my_dict['Java'] = "James Gosling" print(my_dict)
Output:
{'C': 'Dennis Ritchie ', 'C++': 'Bjarne Stroustrup', 'Python': 'Guido van Rossum', 'Java': 'James Gosling'}
Accessing values
To access the value associated with a key, enter the name of the dictionary and its key in square brackets.
# accessing values # get the developer of Python print(my_dict["Python"]) # get the developer of Java print(my_dict["Java"])
Output:
Guido van Rossum James Gosling
Modifying values
To modify the existing pairs, you can do the same process as adding the new pair above. But remember you have to know the key name before modifying otherwise, a new item is inserted.
# modify Python value # change value to Van Rossum my_dict['Python'] = "Van Rossum" print(my_dict["Python"])
Output:
Van Rossum
Looping through dictionary
Dictionary supports looping through three different terms like items, keys, and values:
Looping through items
Use the items() method to loop through all the items inside the dictionary.
# looping through items for key, value in my_dict.items(): print(f'{key} was developed by {value}')
Output:
C was developed by Dennis Ritchie C++ was developed by Bjarne Stroustrup Python was developed by Van Rossum Java was developed by James Gosling
Looping through keys
By default, dictionary objects can loop through keys only. But it is the standard practice to use the keys() method to loop through all keys.
# looping through keys print("All the programming languages") for key in my_dict.keys(): print(key) # OR for key in my_dict: print(key)
Output:
All the programming languages C C++ Python Java .... ....
Looping through values
Use the values() method to loop through all values.
# looping through values print("All the developers") for value in my_dict.values(): print(value)
Output:
All the developers Dennis Ritchie Bjarne Stroustrup Van Rossum James Gosling
Removing key-value pair
Remove single key-value
You can use the del keyword followed by dictionary name and key inside square brackets to delete the key-value pair which are not necessary.
# removing key:value pair # remove Java as key del my_dict["Java"] print(my_dict)
Output:
{'C': 'Dennis Ritchie ', 'C++': 'Bjarne Stroustrup', 'Python': 'Van Rossum'}
Remove all pairs
To clear all the items in the dictionary, use the clear() method as:
# to clear the dictionary my_dict.clear() print(my_dict)
Output:
{}
Delete the object
If you want to delete the dictionary object, then specify the dictionary name only after the del keyword.
# to delete the dictionary object del my_dict print(my_dict)
Output:
Traceback (most recent call last): File "/home/dict_py.py", line 70, in <module> print(my_dict) NameError: name 'my_dict' is not defined