Python | Dictionary methods

In the previous post we learnt Python List and important methods used on Lists. In this post we will learn Python Dictionaries in detail.

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.

  • Open VScode and create new folder python-with-gcptutorials
  • Inside python-with-gcptutorials create file learn_dictionaries.py

vscode-new-file


Python Dictionary

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

  • Strings and numbers can always be used as key.
  • Tuples can be used as keys if they contain only strings, numbers, or tuples; if a tuple contains any mutable object either directly or indirectly, it cannot be used as a key
  • Lists can not be used as keys, since lists can be modified in place various methods.

Create Dictionary

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))
 
Output
   
{'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))
 
Output
   
{'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))
  
 
Output
   
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
<class 'dict'>
 

Python Dictionary Methods

Let's learn some of the most important methods for Python dictionaries with examples.

Python Dictionary clear() Example

clear() 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)
 
Output
   
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
{}
  
 

Python Dictionary copy() Example

copy() 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)
  
 
Output
   
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
 

Python Dictionary fromkeys() Example

fromkeys() 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)
  
 
Output
   
{'apple': 1, 'orange': 1, 'banana': 1}
 

Python Dictionary get() Example

get() 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)
  
 
Output
   
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
16
None
4
not_found
 

Python Dictionary items() Example

items() 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)
  
 
Output
   
{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)
 

Python Dictionary keys() Example

keys() 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)
  
 
Output
   
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
dict_keys([0, 1, 2, 3, 4])
 

Python Dictionary pop() Example

pop() 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)
  
 
Output
   
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
4
{0: 0, 1: 1, 3: 9, 4: 16}
 

Python Dictionary popitem() Example

popitem() 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)
  
 
Output
   
{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)
{}
 

Python Dictionary setdefault() Example

setdefault() 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)
  
 
Output
   
{'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}
 

Python Dictionary update() Example

update() 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)
  
 
Output
   
[[1, 1], [2, 4], [3, 9]]
{4: 8, 5: 10, 6: 12}
{'apple': 1, 'mango': 2}
 

Python Dictionary values() Example

values() 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)
  
  
 
Output
   
{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])