In this tutorial, you’ll learn of everything about Python dictionaries; how they are created, accessing, adding, removing elements from them, and different built-in methods.
Python dictionary is an unordered collection of items. Each item of a dictionary has a key/value pair.
Dictionaries are optimized to retrieve values when the key is known.
In this article, you will learn-
Creating a Python Dictionary
Creating a dictionary is as simple as putting things inside wavy supports {} isolated by commas.
An item has a key and a corresponding value that is communicated as a couple (key: value).
While the qualities can be of any information type and can rehash, keys must be of the changeless sort (string, number, or tuple with unchanging components) and must be unique.
# empty dictionary my_dict = {} # dictionary with integer keys my_dict = {1: 'apple', 2: 'ball'} # dictionary with mixed keys my_dict = {'name': 'salman', 1: [2, 4, 3]} # using dict() my_dict = dict({1:'apple', 2:'ball'}) # from sequence having each item as a pair my_dict = dict([(1,'apple'), (2,'ball')])
As you can see from above, we can also create a dictionary using the built-in dict() function.
Accessing Elements from Dictionary
While indexing is used with other data types to get to esteems, a word reference uses keys. Keys can be utilized either inside square sections [] or with the get() method.
If we use the square sections [], KeyError is brought up on the off chance that a key isn’t found in the word reference. Then again, the get() strategy returns None if the key isn’t found.
# get vs [] for retrieving elements my_dict = {'name': 'khan', 'age': 20} # Output: khan print(my_dict['name']) # Output: 20 print(my_dict.get('age')) # Trying to access keys which doesn't exist throws error # Output None print(my_dict.get('address')) # KeyError print(my_dict['address'])
Output
khan 20 None Traceback (most recent call last): File "<string>", line 15, in <module> print(my_dict['address']) KeyError: 'address'
Changing and Adding Dictionary elements
Dictionaries are mutable. We can include new things or change the estimation of existing things utilizing a task administrator.
On the off chance that the key is as of now present, at that point the current worth gets refreshed. On the off chance that the key is absent, another (key: value) pair is added to the dictionary.
# Changing and adding Dictionary Elements my_dict = {'name': 'khan', 'age': 20} # update value my_dict['age'] = 21 #Output: {'age': 21, 'name': 'khan'} print(my_dict) # add item my_dict['address'] = 'Downtown' # Output: {'address': 'Downtown', 'age': 21, 'name': 'khan'} print(my_dict)
Output
{'name': 'khan', 'age': 21} {'name': 'khan', 'age': 21, 'address': 'Downtown'}
Removing elements from Dictionary
We can remove a particular item in a dictionary by using the pop() method. This method removes an item with the provided key and returns the value.
The pop item() method can be used to remove and return an arbitrary (key, value) item pair from the dictionary. All the items can be removed at once, using the clear() method.
We can also use the del keyword to remove individual items or the entire dictionary itself.
# Removing elements from a dictionary
# create a dictionary
squares = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
# remove a particular item, returns its value
# Output: 16
print(squares.pop(4))
# Output: {1: 1, 2: 4, 3: 9, 5: 25}
print(squares)
# remove an arbitrary item, return (key,value)
# Output: (5, 25)
print(squares.popitem())
# Output: {1: 1, 2: 4, 3: 9}
print(squares)
# remove all items
squares.clear()
# Output: {}
print(squares)
# delete the dictionary itself
del squares
# Throws Error
print(squares)
16 {1: 1, 2: 4, 3: 9, 5: 25} (5, 25) {1: 1, 2: 4, 3: 9} {} Traceback (most recent call last): File "<string>", line 30, in <module> print(squares) NameError: name 'squares' is not defined
Python Dictionary Methods
Methods that are available with a dictionary are tabulated below. Some of them have already been used in the above examples.
Method | Description |
clear() | Removes all items from the dictionary. |
copy() | Returns a shallow copy of the dictionary. |
fromkeys(seq[, v]) | Returns a new dictionary with keys from seq and value equal to v (defaults to None). |
get(key[,d]) | Returns the value of the key. If the key does not exist, returns d (defaults to None). |
items() | Return a new object of the dictionary’s items in (key, value) format. |
keys() | Returns a new object of the dictionary’s keys. |
pop(key[,d]) | Removes the item with the key and returns its value or d if the key is not found. If d is not provided and the key is not found, it raises KeyError. |
popitem() | Removes and returns an arbitrary item (key, value). Raises KeyError if the dictionary is empty. |
setdefault(key[,d]) | Returns the corresponding value if the key is in the dictionary. If not, inserts the key with a value of d and returns d (defaults to None). |
update([other]) | Updates the dictionary with the key/value pairs from other, overwriting existing keys. |
values() | Returns a new object of the dictionary’s values |
Here are a few examples of the use cases of these methods.
# Dictionary Methods
marks = {}.fromkeys(['Math', 'English', 'Science'], 0)
# Output: {'English': 0, 'Math': 0, 'Science': 0}
print(marks)
for item in marks.items():
print(item)
# Output: ['English', 'Math', 'Science']
print(list(sorted(marks.keys())))
Output
{'Math': 0, 'English': 0, 'Science': 0} ('Math', 0) ('English', 0) ('Science', 0) ['English', 'Math', 'Science']
Python Dictionary Comprehension
Dictionary comprehension is an elegant and concise way to make another word reference from an iterable in Python.
Dictionary comprehension comprises an articulation pair (key: value) followed by a for statement inside curly braces {}.
Here is an example to make a dictionary with each item being a pair of a number and its square.
# Dictionary Comprehension
squares = {x: x*x for x in range(6)}
print(squares)
Output
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
This code is equivalent to
squares = {}
for x in range(6):
squares[x] = x*x
print(squares)
Output
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
A dictionary comprehension can optionally contain more for or if statements.
An optional if statement can filter out items to form the new dictionary.
Here are some examples to make a dictionary with only odd items.
# Dictionary Comprehension with if conditional
odd_squares = {x: x*x for x in range(11) if x % 2 == 1}
print(odd_squares)
Output
{1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
Other Dictionary Operations
Dictionary Membership Test
We can test if a key is in a dictionary or not using the keyword. Notice that the membership test is only for the keys and not for the values.
# Membership Test for Dictionary Keys
squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
# Output: True
print(1 in squares)
# Output: True
print(2 not in squares)
# membership tests for key only not value
# Output: False
print(49 in squares)
Output
True True False
Iterating Through a Dictionary
We can iterate through each key in a dictionary using a for a loop.
# Iterating through a Dictionary
squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
for i in squares:
print(squares[i])
Output
1 9 25 49 81
Dictionary Built-in Functions
Built-in functions like all(), any(), len(), cmp(), sorted(), etc. are commonly used with dictionaries to perform different tasks.
Function | Description |
all() | Return True if all keys of the dictionary are True (or if the dictionary is empty). |
any() | Return True if any key of the dictionary is true. If the dictionary is empty, return False. |
len() | Return the length (the number of items) in the dictionary. |
cmp() | Compares items of two dictionaries. (Not available in Python 3) |
sorted() | Return a new sorted list of keys in the dictionary. |
Here are some examples that use built-in functions to work with a dictionary.
# Dictionary Built-in Functions
squares = {0: 0, 1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
# Output: False
print(all(squares))
# Output: True
print(any(squares))
# Output: 6
print(len(squares))
# Output: [0, 1, 3, 5, 7, 9]
print(sorted(squares))
Output
False True 6 [0, 1, 3, 5, 7, 9]
Please feel free to give your comment if you face any difficulty here.
For More Latest Articles Click on Below Link.https://www.worldofitech.com/python-data-types/