Introduction
In Python, a dictionary is an unordered collection of data values that may be use to store data values like a map. Unlike other Data Types that can only carry a single value as an element, a dictionary can hold a key: value pair. The dictionary includes key-value pairs to make it more efficient.
Note:
- Keys in a dictionary don’t allow Polymorphism.
- With the introduction of Python 3.7, Dictionaries were modify to keep insertion order, therefore they are now an ordered collection of data values.
Creating a Python Dictionary
A Dictionary may be create in Python by enclosing a sequence of elements within curly {} braces and separating them with a comma. Dictionary stores pairs of values, one of which is the Key, and the other is the corresponding pair element, which is its Key: value. A dictionary’s values can be of any data type and can be copied, however, keys cannot be copied and must be immutable.
Note: Dictionary keys are case sensitive, which means that the same name but various Key cases will be treat differently.
Code 01: Creating a Dictionary
# Creating a Dictionary
# with Integer Keys
Dictionary = {0: 'Softhunt', 1: '.net', 2: 'By', 3: 'Ranjeet'}
print("\nDictionary with the use of Integer Keys: ")
print(Dictionary)
# Creating a Dictionary
# with Mixed keys
Dictionary = {'Name': 'Ranjeet Kumar Andani', 1: [0, 1, 2, 3, 4, 5]}
print("\nDictionary with the use of Mixed Keys: ")
print(Dictionary)
Output:
Dictionary with the use of Integer Keys: {0: 'Softhunt', 1: '.net', 2: 'By', 3: 'Ranjeet'} Dictionary with the use of Mixed Keys: {'Name': 'Ranjeet Kumar Andani', 1: [0, 1, 2, 3, 4, 5]}
Code 02: The built-in function dict() may also be use to create a dictionary. Simply putting to curly brackets {} creates an empty dictionary.
# welcome to softhunt.net
# Creating an empty Dictionary
Dictionary = {}
print("Empty Dictionary: ")
print(Dictionary)
# Creating a Dictionary
# with Dictionary() method
Dictionary = dict({0: 'Softhunt', 1: '.net', 2: 'By', 3: 'Ranjeet'})
print("\nDictionary with the use of dict(): ")
print(Dictionary)
# Creating a Dictionaryionary
# with each item as a Pair
Dictionary = dict([(0, 'Ranjeet'), (1, 'Kumar'), (2, 'Andani')])
print("\nDictionary with each item as a pair: ")
print(Dictionary)
Output:
Empty Dictionary: {} Dictionary with the use of dict(): {0: 'Softhunt', 1: '.net', 2: 'By', 3: 'Ranjeet'} Dictionary with each item as a pair: {0: 'Ranjeet', 1: 'Kumar', 2: 'Andani'}
Code 03: Nested Dictionary
# welcome to softhunt.net
# Creating a Nested Dictionary
Dictionary = {0: 'Softhunt', 1: '.net',
2:{'i' : 'By', 'ii' : 'Ranjeet', 'iii' : 'Andani'}}
print(Dictionary)
Output:
{0: 'Softhunt', 1: '.net', 2: {'i': 'By', 'ii': 'Ranjeet', 'iii': 'Andani'}}
Adding Elements to a Python Dictionary
The addition of components in Python Dictionary may be done in a variety of methods.
- By declaring value together with the key, for example, dict[Key] = ‘Value’, one value at a time may be added to a Dictionary.
- The built-in update() function may be use to update an existing value in a Dictionary. An existing Dictionary can also have nested key values added to it.
Note: If the key-value pair already exists, the value is changed; otherwise, a new Key with the value is added to the Dictionary.
Code 04:
# welcome to softhunt.net
# Creating an empty Dictionary
Dictionary = {}
print("Empty Dictionary: ", Dictionary)
# Adding elements one at a time
Dictionary[0] = 'Softhunt'
Dictionary[1] = '.net'
print("\nDictionary after adding 2 elements: ", Dictionary)
# Adding set of values
# to a single Key
Dictionary['Value_set'] = 2, 3, 4
print("\nDictionary after adding 3 elements: ", Dictionary)
# Updating existing Key's Value
Dictionary[2] = 'Greetings'
print("\nUpdated key value: ", Dictionary)
# Adding Nested Key value to Dictionary
Dictionary[3] = {'Nested' :{'i' : 'Hello', 'ii' : 'User'}}
print("\nAdding a Nested Key: ", Dictionary)
Output:
Empty Dictionary: {} Dictionary after adding 2 elements: {0: 'Softhunt', 1: '.net'} Dictionary after adding 3 elements: {0: 'Softhunt', 1: '.net', 'Value_set': (2, 3, 4)} Updated key value: {0: 'Softhunt', 1: '.net', 'Value_set': (2, 3, 4), 2: 'Greetings'} Adding a Nested Key: {0: 'Softhunt', 1: '.net', 'Value_set': (2, 3, 4), 2: 'Greetings', 3: {'Nested': {'i': 'Hello', 'ii': 'User'}}}
Accessing elements from a Python Dictionary
In order to access the items of a dictionary refer to its key name. Key can be use inside square brackets.
Code 05: Accessing elements using key
# welcome to softhunt.net
# Python program to demonstrate
# accessing a element from a Dictionary
# Creating a Dictionary
Dictionary = {0: 'Softhunt', 1: '.net', 2: 'By Ranjeet', 'user': 'Greetings to you'}
print("Dictionary", Dictionary)
# accessing a element using key
print("Accessing a element using key:", Dictionary['user'])
# accessing a element using key
print("Accessing a element using key:", Dictionary[2])
Output:
Dictionary {0: 'Softhunt', 1: '.net', 2: 'By Ranjeet', 'user': 'Greetings to you'} Accessing a element using key: Greetings to you Accessing a element using key: By Ranjeet
Code 06: Accessing elements using the get method
# welcome to softhunt.net
# Python program to demonstrate
# accessing a element from a Dictionary
# Creating a Dictionary
Dictionary = {0: 'Softhunt', 1: '.net', 2: 'By Ranjeet', 'user': 'Greetings to you'}
print("Dictionary", Dictionary)
# accessing a element using get()
# method
print("Accessing a element using get:", Dictionary.get('user'))
Output:
Dictionary {0: 'Softhunt', 1: '.net', 2: 'By Ranjeet', 'user': 'Greetings to you'} Accessing a element using get: Greetings to you
Code 07: Accessing Elements of Nested Dictionary
# welcome to softhunt.net
# Creating a Dictionary
Dictionary = {0: 'Softhunt', 1: '.net',
2:{'i' : 'By', 'ii' : 'Ranjeet', 'iii' : 'Andani'}}
print('Dictionary', Dictionary)
# Accessing element using key
print(Dictionary[0])
print(Dictionary[2]['i'])
print(Dictionary[2]['ii'])
Output:
Dictionary {0: 'Softhunt', 1: '.net', 2: {'i': 'By', 'ii': 'Ranjeet', 'iii': 'Andani'}} Softhunt By Ranjeet
Removing Elements from Python Dictionary
There are four methods by which we can remove elements from a dictionary
- Using del keyword
- pop() method
- popitem() method
- Using clear() method
Method 01: Using del keyword
Keys in Python Dictionary may be delete by using the del keyword. Specific values from a dictionary, as well as the whole dictionary, can be delete using the del keyword. Items in a nested dictionary can also be removed by using the del keyword and specifying the nested key and key to be deleted from that nested Dictionary.
Note: Because the del Dict deletes the whole dictionary, printing it after deletion will result in an error.
Code 08:
# welcome to softhunt.net
# Creating a Dictionary
Dictionary = {0: 'Softhunt', 1: '.net',
2:{'i' : 'By', 'ii' : 'Ranjeet', 'iii' : 'Andani'}, 3: 'Greetings'}
print('Initial Dictionary: ', Dictionary)
# Deleting a Key value
del Dictionary[1]
print("\nDeleting a specific key: ", Dictionary)
# Deleting a Key from
# Nested Dictionary
del Dictionary[2]['i']
print("\nDeleting a key from Nested Dictionary: ", Dictionary)
Output:
Initial Dictionary: {0: 'Softhunt', 1: '.net', 2: {'i': 'By', 'ii': 'Ranjeet', 'iii': 'Andani'}, 3: 'Greetings'} Deleting a specific key: {0: 'Softhunt', 2: {'i': 'By', 'ii': 'Ranjeet', 'iii': 'Andani'}, 3: 'Greetings'} Deleting a key from Nested Dictionary: {0: 'Softhunt', 2: {'ii': 'Ranjeet', 'iii': 'Andani'}, 3: 'Greetings'}
Method 02: Using pop() method
The Pop() method returns and deletes the value of the provided key.
Code 09:
# welcome to softhunt.net
# Creating a Dictionary
Dictionary = {0: 'Softhunt', 1: '.net', 2: 'By Ranjeet', 'user': 'Greetings to you'}
print("Dictionary", Dictionary)
# Deleting a key
# using pop() method
pop_element = Dictionary.pop(2)
print('\nDictionary after deletion: ' + str(Dictionary))
print('Value associated to poped key is: ' + str(pop_element))
Output:
Dictionary {0: 'Softhunt', 1: '.net', 2: 'By Ranjeet', 'user': 'Greetings to you'} Dictionary after deletion: {0: 'Softhunt', 1: '.net', 'user': 'Greetings to you'} Value associated to poped key is: By Ranjeet
Method 03: Using popitem() method
The popitem() function retrieves and deletes any arbitrary element (key, value) pair from the dictionary.
Code 10:
# welcome to softhunt.net
# Creating a Dictionary
Dictionary = {0: 'Softhunt', 1: '.net', 2: 'By Ranjeet', 'user': 'Greetings to you'}
print("Dictionary", Dictionary)
# Deleting a key
# using popitem() method
pop_element = Dictionary.popitem()
print('\nDictionary after deletion: ' + str(Dictionary))
print("The arbitrary pair returned is: " + str(pop_element))
Output:
Dictionary {0: 'Softhunt', 1: '.net', 2: 'By Ranjeet', 'user': 'Greetings to you'} Dictionary after deletion: {0: 'Softhunt', 1: '.net', 2: 'By Ranjeet'} The arbitrary pair returned is: ('user', 'Greetings to you')
Method 04: Using clear() method
The clear() method is to delete all elements from a dictionary at once.
Code 11:
# welcome to softhunt.net
# Creating a Dictionary
Dictionary = {0: 'Softhunt', 1: '.net', 2: 'By Ranjeet', 'user': 'Greetings to you'}
print("Dictionary", Dictionary)
# Deleting entire Dictionary
Dictionary.clear()
print("\nDeleting Entire Dictionary: ", Dictionary)
Output:
Dictionary {0: 'Softhunt', 1: '.net', 2: 'By Ranjeet', 'user': 'Greetings to you'} Deleting Entire Dictionary: {}
Conclusion
That’s all for this article, if you have any confusion contact us through our website or email us at [email protected] or by using LinkedIn
Suggested Articles: