Python 3 Data Types – Dictionaries – Explanation with examples

A Dictionary in Python, is data type which is an unordered collection of data in the form of key-value pairs.

A Dictionary acts as a collection of data in which each key has its own value. This data type revolves around the mapping of the key element to the value element.


Creating a Dictionary (Initialization) –

A Dictionary is initialized by placing different key-value pairs as elements under braces “{ }”. Another way is by using the inbuilt function “dict()”. Some of the ways to declare different types of dictionary are explained in the example below –


p={} #Dictionary is Blank, No Keys, No values

q={'a':2, 'b':3, 'c':4} #Keys are Characters and Values are Integers

r={1:'a', 2:'b', 3:'c'} #Here, Keys are Integers and values are Characters

s={'id':24, 'name':'Jim', 'marks':[10,9,5,9]} #Keys and Values are Different Data types

t=dict([(1,'a'),(2,'b),(3,'c')]) #This is the same as dictionary r

u=dict({'a':2, 'b':3, 'c':4}) #This is the same as dictionary q

Here, the dictionaries t and r, q and u are same. But the declaration methods are different.


Accessing Dictionary Elements –

A Dictionary consists of both keys and values. Accessing the value which is mapped alongside a key can be done in two ways, Indexing and get().

The value mapped to the key ‘k’ can be accessed by using dictname[k]. Here dictname is the name of the dictionary and ‘k’ is the key which has to be accessed.

Another way to access dictionary value is by using the get(key) method which returns the value mapped to ‘key’ in the dictionary.

Below example will explain these two methods-

x={'a':2, 'b':3, 'c':4}
print(x['b']) #Print the value corresponding to the key 'b' (Indexing)
print(x.get('a')) #Print the value corresponding to the key 'a'
Output:-
3
2

If we try to access a ‘key’ which is not present in the dictionary, then it throws a Runtime error.

x={'a':2, 'b':3, 'c':4}
print(x['d']) #Throws a Runtime Error as the key 'd' is not present in Dictionary

The above code generates an error, No output is generated.

Accessing all the keys and Values –

The methods keys() and values() return a list of all the keys and values present in the dictionary, respectively (Not necessarily in order).

x={'a':2, 'b':3, 'c':4}
print(x.keys()) #Print all the keys present in the dictionary x
print(x.values()) #Print all the values present in the dictionary x
Output:-
['a','c','b']
[2,4,3]

Adding and Updating the values –

New values in a dictionary can be added after its declaration. If the key is already present, the value is updated. Taking a look at the following example –

x={'a':2, 'b':3, 'c':4}
x['d']=5 #Adding a new key-value pair ('d':5) to x 
x['a']=1 #Updating the value corresponding to key 'a', i.e change 2 to 1
print(x)
Output:-
{'a': 1, 'c': 4, 'b': 3, 'd': 5}

From the above example, we added a new key-value pair (‘d’:5) to the existing dictionary x, just by assigning the value. If the same process is done to an existing key, the existing value is updated by the new value.


 Deleting the values –

Values in a dictionary can be deleted by using the method pop(). This method takes the key as an argument and deletes that particular key-value pair present in the dictionary. To clear the whole dictionary, the method clear() is used. Taking a look at the example–

x={'a':2, 'b':3, 'c':4}
x['d']=5 #Adds a new key-value pair ('d':5) to x 
x['a']=1 #Updates the value corresponding to key 'a', i.e changes 2 to 1
print(x)
x.pop('b') #Deletes the key-value pair ('b':3)
print(x)
x.pop('a') #Deletes the key-value pair ('a':1)
print(x)
Output:-
{'a': 1, 'c': 4, 'b': 3, 'd': 5}
{'a': 1, 'c': 4, 'd': 5}
{'c': 4, 'd': 5}

The pop() method generates a Runtime Error if the key to deleted is not present in the dictionary. This is called Underflow situation in which the item to be deleted does not exist.

x={'a':2, 'b':3, 'c':4}
x.pop('d') #Attempts to delete key-value pair where key='d'. Runtime error.
print(x)

The above code generates a Runtime Error because the key ‘d is not present in the dictionary x.


 Iterating through a Dictionary –

Printing all the key-value pairs inside dictionary can be done by using a simple for loop. Checking if a key is present inside the dictionary is done by using the in keyword.

x={'a':2, 'b':3, 'c':4, 'd':5}
if 'b' in x:
    print("Found")
for i in x:
    print(i,x[i])
Output:-
Found
a 2
c 4
b 3
d 5

Now if we need to print or operate on only keys/values, using the methods keys()  and values() is the most efficient way as described above.
Some commonly used built in functions are len(), max(), min(), sorted(). Below example clarifies all these methods.

x={'a':2, 'b':3, 'c':4, 'd':5}
print(len(x)) #Prints number of keys present
print(max(x)) #Prints Maximum key
print(min(x)) #Prints Minimum key
print(sorted(x)) #Prints all the keys in Ascending order
print(sorted(x,reverse=True)) #Prints all the keys in Descending order

Output:-
4
d
a
['a', 'b', 'c', 'd']
['d', 'c', 'b', 'a']

That’s all for this tutorial. If you have any doubts, please post them in the comments section. Any ideas/suggestions are welcome.

Do not forget to share, like and spread the knowledge. 🙂