In the previous post we learnt Python List and important methods used on Lists. In this post we will learn Python Dictionaries in detail.
Topics Covered
Optional: Creating chapter-wise Python files
Let's create a directory that will house fresh Python files with code samples from each post in order to keep track of what we've learned so far from each one. For the purpose of keeping all learning in one location, this step is optional but is advised to set up.
Python Dictionaries are a set of key: value pairs. Dictionaries are indexed by keys, unlike sequences which are indexed by a range of numbers.
Dictionary Keys
Dictionary can be created using a pair of braces, placing a comma-separated list of key:value pairs within the braces adds initial key:value pairs to the dictionary. Write below code to learn_dictionaries.py and run the script.
Using {}
# dictionary using {}
fruits = {"apple":1, "mango":3, "banana": 5}
print(fruits)
print(type(fruits))
{'apple': 1, 'mango': 3, 'banana': 5}
<class 'dict'>
Using dict() constructor
# dictionary using dict()
fruits = dict([("apple", 1), ("mango", 3), ("banana", 4)])
print(fruits)
print(type(fruits))
{'apple': 1, 'mango': 3, 'banana': 4}
<class 'dict'>
Using dict comprehensions
# dictionary using comprehension
numbers = {x: x**2 for x in range(5)}
print(numbers)
print(type(numbers))
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
<class 'dict'>
Let's learn some of the most important methods for Python dictionaries with examples.
clear()
Exampleclear()
method of python dictionary removes all items from the dictionary.
# dictionary clear() method
numbers = {x: x**2 for x in range(5)}
print(numbers)
numbers.clear()
print(numbers)
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
{}
copy()
Examplecopy()
method of python dictionary returns a shallow copy of dictionary.
# dictionary copy() method
numbers = {x: x**2 for x in range(5)}
print(numbers)
numbers_copy = numbers.copy()
print(numbers_copy)
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
fromkeys()
Examplefromkeys()
method of python dictionary creates a new dictionary with keys from iterable and values set to value.
# dictionary fromkeys() method
empty_dict = {}
my_list = ["apple", "orange", "banana"]
my_dict = empty_dict.fromkeys(my_list, 1)
print(my_dict)
{'apple': 1, 'orange': 1, 'banana': 1}
get()
Exampleget()
method of python dictionary returns the value of given Key, if key is not found it returns None
or given default value.
# dictionary get() method
numbers = {x: x**2 for x in range(5)}
print(numbers)
# key is present in dictionary
value_1 = numbers.get(4)
print(value_1)
# key not in dictionary
value_2 = numbers.get(6)
print(value_2)
# get with default value
value_3 = numbers.get(2, "not_found")
print(value_3)
value_4 = numbers.get(6, "not_found")
print(value_4)
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
16
None
4
not_found
items()
Exampleitems()
method of python dictionary provides a set-like object providing a view on dictionary items.
# dictionary items() method
numbers = {x: x**2 for x in range(5)}
print(numbers)
items = numbers.items()
print(items)
print(type(items))
for item in items:
print(item)
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
dict_items([(0, 0), (1, 1), (2, 4), (3, 9), (4, 16)])
<class 'dict_items'>
(0, 0)
(1, 1)
(2, 4)
(3, 9)
(4, 16)
keys()
Examplekeys()
method of python dictionary provides a set-like object providing a view on dictionary keys.
# dictionary keys() method
numbers = {x: x**2 for x in range(5)}
print(numbers)
dict_keys = numbers.keys()
print(dict_keys)
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
dict_keys([0, 1, 2, 3, 4])
pop()
Examplepop()
method of python dictionary removes specified key and returns the corresponding value.
# dictionary pop() method
numbers = {x: x**2 for x in range(5)}
print(numbers)
removed_value = numbers.pop(2)
print(removed_value)
print(numbers)
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
4
{0: 0, 1: 1, 3: 9, 4: 16}
popitem()
Examplepopitem()
method of python removes and returns a (key, value) pair from the dictionary. Pairs are returned in LIFO (last-in, first-out) order.
# dictionary popitem() method
numbers = {x: x**2 for x in range(5)}
print(numbers)
for num in range(len(numbers)):
removed_pair = numbers.popitem()
print(removed_pair)
print(numbers)
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
(4, 16)
{0: 0, 1: 1, 2: 4, 3: 9}
(3, 9)
{0: 0, 1: 1, 2: 4}
(2, 4)
{0: 0, 1: 1}
(1, 1)
{0: 0}
(0, 0)
{}
setdefault()
Examplesetdefault()
method of python dictionary inserts the given key with the default value if key is not in the dictionary, if key is in the dictionary than it returns the value of key.
# dictionary setdefault() method
fruits = {"orange": 3, "apple": 4, "mango": 2, "banana": 5}
print(fruits)
# insert new key
res = fruits.setdefault("grapes", 10)
print(res)
print(fruits)
# setdefault on existing key
res = fruits.setdefault("mango", 10)
print(res)
print(fruits)
{'orange': 3, 'apple': 4, 'mango': 2, 'banana': 5}
10
{'orange': 3, 'apple': 4, 'mango': 2, 'banana': 5, 'grapes': 10}
2
{'orange': 3, 'apple': 4, 'mango': 2, 'banana': 5, 'grapes': 10}
update()
Exampleupdate()
method of python dictionary updates the dictionary with the key/value pairs from another dictionary object or an iterable of key/value pairs (as tuples or other iterables of length two) and overwrites existing keys.
# dictionary update() method
numbers = {}
fruits = {}
squares = [[1, 1], [2, 4], [3, 9]]
print(squares)
two_x = ((4, 8), (5, 10), (6, 12))
numbers.update(two_x)
print(numbers)
fruits.update(apple=1, mango=2)
print(fruits)
[[1, 1], [2, 4], [3, 9]]
{4: 8, 5: 10, 6: 12}
{'apple': 1, 'mango': 2}
values()
Examplevalues()
method of python dictionary provides a view of dictionary values.
# dictionary values() method
numbers = {x: x**2 for x in range(10)}
print(numbers)
all_values = numbers.values()
print(all_values)
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
dict_values([0, 1, 4, 9, 16, 25, 36, 49, 64, 81])