Table of Contents
Introduction Creation of a dictionary Built-in function dict () Accessing Dictionary Elements Accessing elements from nested dictionaries Difference between square brackets [] and using get() function Removing dictionary elements Iterating over a dictionary Modification and Addition of dictionary Some built-in methods of dictionary ConclusionWhat are Dictionaries in Python?
A dictionary is a composite data type offered by Python, a collection of items comparable to a list. Dictionary in Python is a collection of key values used to store data like a map, unlike other data types, which hold only a single value as an element.
The main objective of this blog is to help students learn how to access and manage dictionary data and the fundamental features of Python dictionaries. On completing this article, the student would have a solid understanding of when and how to utilize a dictionary as a data type.
Introduction
In Python, data structures allow us to manage and perform actions on data collection. Data structures make it simpler to manipulate collections of data.
In Python basically, we have the following 4 data Structures namely
- List
- Dictionary
- Tuple
- Set
In this article, we will be focusing on one of the most important and crucial data structures of Python i.e. Dictionary
Python Dictionary is a set of values in an unordered collection. They are incredibly adaptable and provide effective data storage and retrieval.
They may be used to store anything, ranging from basic values (such as strings or integers) to more complicated data structures (like lists or objects).
A dictionary has a key/value pair for each entry. The dictionary includes the key value to improve its optimization for retrieving values when the key is known.
Creation of a dictionary
A list of elements can be assigned inside curly brackets {} to build a Python dictionary.
There is a “comma” (,) between them. You can discover a pair of values in a dictionary where one is the key and the other is the corresponding pair value element, also known as Key:value pair.
The values you find in a dictionary can be of different data types (string, number, tuple) and can be duplicated, but the keys must be unique and cannot be duplicated.
Creating Empty Dictionary
dict = {}
print("Empty Dictionary:" ,dict)
Empty Dictionary: {}
Creating Dictionary with Integer keys
dict = {1: 'Codingal', 2: 'Kids', 3: 'Coding'}
print("Dictionary: ", dict)
Dictionary: {1: 'Codingal', 2: 'Kids', 3: 'Coding'}
Creating Dictionary with Mixed keys
dict = {'Name': 'Codingal', 1: [9, 2020, 2, 29]}
print("Dictionary: " ,dict)
Dictionary: {'Name': 'Codingal', 1: [9, 2020, 2, 29]}
Built-in function dict ()
The built-in function dict () in Python can also be employed to create a dictionary.
dict1 = dict({1: 'Codingal', 2: 'Kids', 3: 'Coding'})
print("Dictionary: ", dict1)
Dictionary: {1: 'Codingal', 2: 'Kids', 3: 'Coding'}
Creating Dictionary with each item as a Pair
dict1 = dict([(1, 'Codingal'), (2, 'Penguin')])
print("Dictionary :" , dict1)
Dictionary : {1: 'Codingal', 2: 'Penguin'}
Creating a Nested Dictionary
dict1 = {1: 'Codingal', 2: 'kids', 3:{'a' : 'Penguin', 'b' : 'coding', 'c' : 'best'}}
print(dict1)
{1: 'Codingal', 2: 'kids', 3: {'a': 'Penguin', 'b': 'coding', 'c': 'best'}}
Accessing Dictionary Elements
While other data types use indexing to obtain values, dictionaries employ keys. Keys can be used either using the get() function or within square brackets [].
Using square brackets []:
In Python, enter the dictionary name and the item’s key in square brackets to obtain an item’s value.
dict = {1: 'Codingal', 2: 'Kids', 3: 'Coding'}
print("Value of element number 1 in dictonary is:" ,dict[1]
Value of element number 1 in dictonary is: Codingal
Using get() function:
dict = {1: 'Codingal', 2: 'Kids', 3: 'Coding'}
print("Value of element number 2 in dictonary is:" ,dict.get(2))
Value of element number 2 in dictonary is: Kids
Accessing elements from nested dictionaries
Example 1
dict1 = {1: 'Codingal', 2: 'kids', 3:{'a' : 'Penguin', 'b' : 'coding', 'c' : 'best'}}
print(dict1[3])
{'a': 'Penguin', 'b': 'coding', 'c': 'best'}
Example 2
dict1 = {1: 'Codingal', 2: 'kids', 3:{'a' : 'Penguin', 'b' : 'coding', 'c' : 'best'}}
print(dict1[3]['a'])
Penguin
Difference between square brackets [] and using get() function:
There is a difference between using square brackets [] and using get() function, when a key is not found in the dictionary, KeyError is generated if we use the square brackets [] and on the other hand, if the key cannot be retrieved, the get() function returns None.
Example of [] bracket
dict = {1: 'Codingal', 2: 'Kids', 3: 'Coding'}
print("Using square brackets:" ,dict[4] )
Traceback (most recent call last):
File "main.py", line 2, in <module>
print("Using square brackets:" ,dict[4] )
KeyError: 4
Example of get() function
dict = {1: 'Codingal', 2: 'Kids', 3: 'Coding'}
print("Using get:" ,dict.get(4) )
Using get: None
Removing dictionary elements
Removing the element using del keyword
Using the del keyword, we can remove keys from a Python dictionary.
In fact, we can delete the entire dictionary or just a few particular items by using the del keyword. The del keyword can also be used to remove items from a nested dictionary.
dict = {1: 'Codingal', 2: 'Kids', 3: 'Coding'}
del dict[2]
print("Using del keyword:" ,dict)
Using del keyword: {1: 'Codingal', 3: 'Coding'}
Removing Nested elements using del keyword
dict1 = {1: 'Codingal', 2: 'kids', 3:{'a' : 'Penguin', 'b' : 'coding', 'c' : 'best'}}
del dict1[3]['a']
print("Deleting nested elements using del keyword:" ,dict1)
Deleting nested elements using del keyword: {1: 'Codingal', 2: 'kids', 3: {'b': 'coding', 'c': 'best'}}
Removing the elements using pop() method
The pop() function allows you to both return and remove the value of the provided key.
Example 1
dict = {1: 'Codingal', 2: 'Kids', 3: 'Coding'}
dict1=dict.pop(2)
print("Removal of element using pop:" ,dict)
Removal of element using pop: {1: 'Codingal', 3: 'Coding'}
Example 2:
dict = {1: 'Codingal', 2: 'Kids', 3: 'Coding'}
dict1=dict.pop(2)
print("Returning of element using pop:" ,dict1)
Returning of element using pop: Kids
Removing the elements using popitem() method
One can delete and return an arbitrary (key, value) item pair from the dictionary using the popitem() function.
Example 1:
dict = {1: 'Codingal', 2: 'Kids', 3: 'Coding'}
dict1=dict.popitem()
print("Removal of element using popitem:" ,dict)
Removal of element using popitem: {1: 'Codingal', 2: 'Kids'}
Example 2:
dict = {1: 'Codingal', 2: 'Kids', 3: 'Coding'}
dict1=dict.popitem()
print("Returning of element using popitem:" ,dict1)
Returning of element using popitem: (3, 'Coding')
Removing all elements using clear() method
The clear() function may be used to delete every item at once.
dict = {1: 'Codingal', 2: 'Kids', 3: 'Coding'}
dict1=dict.clear()
print("Removal of all element using clear:" ,dict)
Removal of all element using clear: {}
Iterating over a dictionary
A for loop may be used to repeatedly iterate through each key in a dictionary.
dict = {1: 'Codingal', 2: 'Kids', 3: 'Coding'}
for i in dict:
print("Key:",i, "Value:",dict[i])
Key: 1 Value: Codingal
Key: 2 Value: Kids
Key: 3 Value: Coding
Modification and Addition of dictionary
Dictionaries may alter. Using an assignment operator, we may add new items or modify the values of already existing items.
If the key is already there, the value that is already there is changed. A new (key: value) pair is added to the dictionary if the key is absent.
Example 1: Updating the element in dictionary
dict = {1: 'Codingal', 2: 'Kids', 3: 'Coding'}
dict[3]='Love'
print("Updating a Dictionary:",dict)
Updating a Dictionary: {1: 'Codingal', 2: 'Kids', 3: 'Love'}
Example 2: Adding the element in dictionary
dict = {1: 'Codingal', 2: 'Kids', 3: 'Coding'}
dict[4]='Love'
print("Adding a Dictionary:",dict)
Adding a Dictionary: {1: 'Codingal', 2: 'Kids', 3: 'Coding', 4: 'Love'}
Some built-in methods of dictionary
There are several methods we can employ while using dictionaries.
The most beneficial ones are .keys(), .values(), and .items ()
keys()
A list of every key in the dictionary is returned by the .keys() function.
dict = {1: 'Codingal', 2: 'Kids', 3: 'Coding'}
print("Keys of Dictionary:",dict.keys())
Keys of Dictionary: dict_keys([1, 2, 3])
values()
A list of all the values in the dictionary is returned by the.values() function.
dict = {1: 'Codingal', 2: 'Kids', 3: 'Coding'}
print("Values of Dictionary:",dict.values())
Values of Dictionary: dict_values(['Codingal', 'Kids', 'Coding'])
item()
A list of tuples, each of which contains a key-value pair, is what the .items() function delivers.
dict = {1: 'Codingal', 2: 'Kids', 3: 'Coding'}
print("Items of Dictionary:", dict.items())
Items of Dictionary: dict_items([(1, 'Codingal'), (2, 'Kids'), (3, 'Coding')])
Conclusion
In Python, dictionaries are significant and highly effective data structures that employ keys for indexing. Since they are key-value pairs in an unordered sequence, the order is not retained.
The keys cannot be changed. One can create, add, update, remove and access values from a dictionary using the key:value pair.
Python helps us to write various computer codes to obtain the desired output. The syntax of Python makes it easy for beginners to code any set of instructions.
Coding for kids has many beneficial advantages that develop cognitive abilities, enhance communication and entrepreneurship skills, and stimulate creativity. In addition, children can learn Python programming to build technical skills for the future.
Python programming for kids fosters their interest in learning and executing various code snippets.
Codingal’s Python for kids course is designed so that kids find it extremely easy to step into the world of coding. Try a free class today!