Accessing Elements From Dictionary
Accessing Elements From Dictionary
While indexing is used with other data types to access values, a dictionary
uses keys . Keys can be used either inside square brackets [] or with
the get() method.
If we use the square brackets [] , KeyError is raised in case a key is not found in
the dictionary. On the other hand, the get() method returns None if the key is not
found.
# Output: Jack
print(my_dict['name'])
# Output: 26
print(my_dict.get('age'))
# KeyError
print(my_dict['address'])
Output
Jack
26
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 add new items or change the value of existing
items using an assignment operator.
If the key is already present, then the existing value gets updated. In case the
key is not present, a new (key: value) pair is added to the dictionary.
# update value
my_dict['age'] = 27
# add item
my_dict['address'] = 'Downtown'
Output
# create a dictionary
squares = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
# Output: {1: 1, 2: 4, 3: 9}
print(squares)
# Output: {}
print(squares)
# Throws Error
print(squares)
Output
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
Method Description
fromkeys(seq[,
Returns a new dictionary with keys from seq and value equal to v (defaults to N
v])
get(key[,d]) Returns the value of the key . If the key does not exist, returns d (defaults to No
items() Return a new object of the dictionary's items in (key, value) format.
Removes the item with the key and returns its value or d if key is not found. If
pop(key[,d])
provided and the key is not found, it raises KeyError .
Removes and returns an arbitrary item (key, value). Raises KeyError if the dic
popitem()
empty.
Returns the corresponding value if the key is in the dictionary. If not, inserts th
setdefault(key[,d])
with a value of d and returns d (defaults to None ).
update([other]) Updates the dictionary with the key/value pairs from other , overwriting existin
# Dictionary Methods
marks = {}.fromkeys(['Math', 'English', 'Science'], 0)
# Output: {'English': 0, 'Math': 0, 'Science': 0}
print(marks)
Output
# Dictionary Comprehension
squares = {x: x*x for x in range(6)}
print(squares)
Output
squares = {}
for x in range(6):
squares[x] = x*x
print(squares)
Output
print(odd_squares)
Output
We can test if a key is in a dictionary or not using the keyword in . Notice that the
membership test is only for the keys and not for the values .
# Output: True
print(1 in squares)
# Output: True
print(2 not in squares)
Output
True
True
False
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
Here are some examples that use built-in functions to work with a dictionary.
# 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]