Dictionary in python

Introduction

Dictionary in python is another useful built-in data type. The dictionary is an unordered collection of key-value pairs separated by a comma that is enclosed by curly braces. Values can be any python object but the key needs to be hashable or immutable objects that are unique.

A dictionary is a mutable object meaning that we can add or remove elements from a dictionary. 

Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type; strings and numbers can always be keys. In addition, tuples can be also 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. On contrary, you can’t use lists as keys, since lists can be modified in place using index assignments, slice assignments, or methods like append() and extend().

You will understand clearly when we move further about learning dictionaries in python.

How to create a dictionary

It is best to think of a dictionary as a set of key: value pairs, with the requirement that the keys are unique (within one dictionary). Let’s see how to create three types of dictionaries in python with an example.

1. Creating an empty dictionary in python

Example 1:

dict1 = {}
print(dict1)
print(type(dict1))

# Output
{}
<class 'dict'>

Example 2:

dict1 = dict()   # Using dictionary constructor
print(dict1)
print(type(dict1))

# Output
{}
<class 'dict'>

2. Non-empty dictionary in python

Example:

person = {'name': 'Dawa', 'age': 30 }
print(person)

# Output
{'name': 'Dawa', 'age': 30}

In the above example, ‘name‘ and ‘age‘ are keys and ‘Dawa‘ and 30 are values.

3. Nested dictionary in python

Example:

person = {
    1:{'name':'Dawa', 'age':30},
    2:{'name':'Penjor', 'age':40}
        }
print(person)

# Output
{1: {'name': 'Dawa', 'age': 30}, 2: {'name': 'Penjor', 'age': 40}}
Properties of the dictionary key

Dictionary values have no restrictions. They can be any arbitrary Python object, either standard objects or user-defined objects. However, it is not the same as dictionary keys.

1. Key needs to be hashable or immutable objects and unique.

Example:

person = {['name']: 'Dawa', 'age': 30}
print(person)

Output:

Traceback (most recent call last):
File “C:\Users\Dawa Penjor\Desktop\test.py”, line 1, in
person = {[‘name’]: ‘Dawa’, ‘age’: 30}
TypeError: unhashable type: ‘list’

In the above example, you will get TypeError: unhashable type: ‘list’. This is because one of the keys [‘name’] is a list that is mutable. Keys need to be immutable types that can be either string, number, or tuple data types.

2. No duplicate keys are allowed. If there is a duplicate key, the last one will be executed.

Example: (There is a duplicate ‘age’ key. Only the last will be executed).

person = {'name': 'Dawa', 'age': 30, 'age': 40}
print(person)

Output:

{'name': 'Dawa', 'age': 40}
Dictionary operations:
Loop through a dictionary

You can loop through a dictionary using a for loop.

Example:

Text_Editor = {'C': 'TurboC', 'Python':'Pycham', 'Java':'Elipse', 'HTML':'sublime'}
for i in Text_Editor:
    print(i)

Output:

C
Python
Java
HTML

To loop over two or more sequences at the same time, the entries can be paired with the zip() function.

Example:

language = ['Python', 'Java', 'HTML']
text_editor = ['Pycham', 'Elipse', 'Notepad++']
for k, l in zip(language, text_editor):
    print(k, ":", l)

Output:

Python : Pycham
Java : Elipse
HTML : Notepad++
reversed(dictview)

Changed in version 3.8: Dictionary views are now reversible.

Returns a reverse iterator over the keys, values, or items of the dictionary. The view will be iterated in reverse order of the insertion.

Example:

nums = {"one": 1, "two": 2, "three": 3, "four": 4}
print(f"original insertion: {nums}")
print(f"keys in reversed order: {list(reversed(nums))}")
print(f"values in reversed order:{list(reversed(nums.values()))}")
print(f"items in reversed order:{list(reversed(nums.items()))}")

Output:

original insertion: {'one': 1, 'two': 2, 'three': 3, 'four': 4}
keys in reversed order: ['four', 'three', 'two', 'one']
values in reversed order:[4, 3, 2, 1]
items in reversed order:[('four', 4), ('three', 3), ('two', 2), ('one', 1)]
Check if Key Exist

Use membership operators; in or not in to determine if a specified key is present in a dictionary or not.

Example:

Text_Editor = {
    'C': 'TurboC', 
    'Python':'Pycham', 
    'Java':'Elipse', 
    'HTML':'sublime'
    }
if 'HTML' in Text_Editor:
    print('HTML key is in the dictionary')

Output:

HTML key is in the dictionary
Accessing elements from Dictionary

There are three ways where we can access elements from the dictionary:

1. Referring key name

In order to access the items of a dictionary refer to its key name. Key can be used inside square brackets.

Example:

Text_Editor = {
    'C': 'TurboC', 
    'Python':'Pycham', 
    'Java':'Elipse', 
    'HTML':'sublime'
    }
print(Text_Editor['Python'])

Output:

Pycham

2. There is a method called get() that will also help in accessing the element from a dictionary. It was discussed later under the dictionary method.

3. Accessing an element of a nested dictionary

In order to access the value of any key in a nested dictionary, use indexing [] syntax.

Example:

Text_Editor = {
    'C': 'TurboC', 
    'Python':'Pycham', 
    'Java':'Elipse', 
    'HTML':{
        'HTML4':'Notepad',
        'HTML5':'Notepad++'
    }
    }
print(Text_Editor['HTML']['HTML4'])

Output:

Notepad
Adding and Updating the dictionary

Adding an item to the dictionary is done by using a new index key and assigning a value to it. If the key is already present, then the existing value gets updated.

Example:

Text_Editor = {
    'C': 'Turbo c', 
    'Python':'Pycham', 
    'Java':'Elipse', 
    'HTML':'Notepad++'
}
print(f"Initial: {Text_Editor}")
Text_Editor['Python'] = 'VS Code'  # Updating values of the keys.
Text_Editor['C++'] = 'Turbo c'  # Adding new element in dict
print('updated =', Text_Editor)

Output:

Initial: {'C': 'Turbo c', 'Python': 'Pycham', 'Java': 'Elipse', 'HTML': 'Notepad++'}
updated = {'C': 'Turbo c', 'Python': 'VS Code', 'Java': 'Elipse', 'HTML': 'Notepad++', 'C++': 'Turbo c'}
Delete Dictionary element

We can use the del keyword to remove individual items or the entire dictionary itself.

Example:

person = {'name':'Dawa', 'age': 30}
print(person)

# Deleting age key
del person['age']
print(person)

Output:

{'name': 'Dawa', 'age': 30}
{'name': 'Dawa'}
Finding the length of a dictionary

To determine how many items (key-value pairs) a dictionary has, use the len() function.

Example:

person = {'name':'Dawa', 'age': 30}
print(len(person))

Output:

2
Dictionary method

Dictionary in python has 11 built-in methods that you can use. We will discuss them all with an example:

Clear

Removes all items from the dictionary.

Example:

person = {'name': 'Dawa', 'Country': 'Bhutan', 'age':30}
person.clear()
print(person)

Output:
{}   # Output is empty because dictionary is cleared

Copy

Returns a shallow copy of the dictionary.

Example:

person = {'name': 'Dawa', 'Country': 'Bhutan', 'age':30}
address = person.copy()
print(address)        # Address contains the copy of person

Output:

{'name': 'Dawa', 'Country': 'Bhutan', 'age': 30}
Fromkeys(iterable, value=none)

Using the fromkeys method we can create dictionaries with keys from the iterable, that is nothing but dictionaries using a list, tuple, range function, or any other iterable. If nothing is specified as a value, None will be assigned to all the keys while looping/iterating over it.

Example:

names = ['dawa', 'sonam', 'karma']
print(dict.fromkeys(names)) # Value assigned by default ie None
print(dict.fromkeys(range(1, 5), 10)) # Value assigned is 10

Output:

{'dawa': None, 'sonam': None, 'karma': None}
{1: 10, 2: 10, 3: 10, 4: 10}
Get(key, default=None)

Returns the value for the key if a key is in the dictionary, else the default message.

Example:

Text_Editor = {
    'C': 'TurboC', 
    'Python':'Pycham', 
    'Java':'Elipse', 
    'HTML':'sublime'
    }
print(Text_Editor.get('Java'))
print(Text_Editor.get('C', 'Key doesnot exist in the dictionary'))
#since JavaScript is not in the dictionary, it will return default message.
print(Text_Editor.get('JavaScript', 'Key doesnot exist in the dictionary')) 

Output:

Elipse
TurboC
Key doesnot exist in the dictionary
Items

When looping through dictionaries, the key and corresponding value can be retrieved at the same time using the items() method.

Example:

Text_Editor = {
    'Python':'Pycham', 
    'Java':'Elipse', 
    'HTML':'Notepad++'
}
for k, l in Text_Editor.items():
    print(f'key:{k} value:{l}')

Output:

key:Python value:Pycham
key:Java value:Elipse
key:HTML value:Notepad++
Keys

This method returns only the keys of the dictionary.

Example:

Text_Editor = {
    'Python':'Pycham', 
    'Java':'Elipse', 
    'HTML':'Notepad++'
}
print(Text_Editor.keys())

Output;

dict_keys(['Python', 'Java', 'HTML'])
Values

This method returns only the values of the dictionary.

Example:

Text_Editor = {
    'Python':'Pycham', 
    'Java':'Elipse', 
    'HTML':'Notepad++'
}
print(Text_Editor.values())

Output:

dict_values(['Pycham', 'Elipse', 'Notepad++']) 
pop(key, default)

If the key is in the dictionary, it removes and returns its corresponding value, else returns default. If the default is not given and the key is not in the dictionary, a KeyError is raised.

Example:

info = {'Language': 'Python', 'Job':'Developer'}
info.pop('Language')
print(info)

Output:

{'Job': 'Developer'}
Popitem

Popitem() method removes and returns a (key, value) pair from the dictionary as a 2-tuple. Pairs are returned in LIFO(last in, first out) order. Raises KeyError if the dictionary is empty.

Changed in version 3.7: LIFO order is now guaranteed. In prior versions, the popitem() would return an arbitrary key/value pair.

Example:

info = {'Language': 'Python', 'Job':'Developer'}
p = info.popitem()
print(p)

Output:

('Job', 'Developer')  #last item from the dictionary is popped.

Setdefault (key[, default])

If the key is in the dictionary, return its value, otherwise, it will return a default value.

Example 1:

info = {'Language': 'Python', 'Job':'Developer', 'name':'Dawa'}
info.setdefault('Job')
print(info)

Output:
{'Language': 'Python', 'Job': 'Developer', 'name': 'Dawa'}

Example 2:

info = {'Language': 'Python', 'Job':'Developer', 'name':'Dawa'}
info.setdefault('age', 30)
print(info)

Update:
{'Language': 'Python', 'Job': 'Developer', 'name': 'Dawa', 'age': 30}

Update

Updates the dictionary with the key/value pairs from others, overwriting existing keys.

update() accepts either another dictionary object or an iterable of key/value pairs (as tuples or other iterable of length two). If keyword arguments are specified, the dictionary is then updated with those key/value pairs.

Example:

person = {'name': 'Dawa', 'Address': 'Bhutan'}
info = {'Language': 'Python', 'Job':'Developer'}
person.update(info)
print(person)

Output:

{'name': 'Dawa', 'Address': 'Bhutan', 'Language': 'Python', 'Job': 'Developer'}