Dictionaries are unordered storage units, used to store key-value pairs. What’s that you ask? Well, like in lists we can access an item using it’s index, in dictionaries we can access items using the keys. A dictionary is made using {} pair. Let’s make a dictionary-


The syntax is – {key1:value1, key2:value2…}.

Notice how we accessed the values using the keys and printed them out. We will get the following as the output when we run the above piece of code-

1 2 3

If you want to print the entire dictionary, just write – print (name of the dictionary), and it will print it out.

Need for Dictionaries

Dictionaries are required when we want to access items without knowing their index values. Say, a database which contains information about the students in a school. So, if we want any information about a student, instead of looking everywhere for his/her index number in the dataset, we can access it directly using his/her name. The same logic is applied in case of dictionaries.

How to add, change and delete a key:value pair?

We can add a key-value pair, say ‘d’:4, to our above dictionary simply by doing –


Note that dictionaries cannot be sorted in any manner, so the elements are unsorted.

Now, we can delete a key-value pair using the pop() method. The basic syntax is – dictionary_name.pop(key of key-value pair which is to be removed). Let’s delete the ‘b’ pair from the dictionary  my_dict-


When we run it, we get-

{'a': 1, 'd': 4, 'c': 3}

We can change the value at a particular place by doing dictionary_name[key whose value is to be changed] = new_value. Let’s change the value of ‘a’ to 12.


Length of Dictionaries

Length of dictionaries can be found out using the len() keyword. We will get the length as 3 when we run the following code-


Checking if a value is present or not

We use the keyword to check the presence of a key in the dictionary-

print('a' in my_dict)
print('z' in my_dict)

And we will get the following output-



keys() method

The keys() method is used to get all the keys of a dictionary.


We get the following output when we run it-

dict_keys(['d', 'c', 'a'])

values() method

The values() method is used to get all the values of a dictionary.


We get the following output when we run it-

dict_values([12, 3, 4])

items() method

The items() method is used to get all the key-value pairs of a dictionary.


We get the following output when we run it-

dict_items([('c', 3), ('a', 12), ('d', 4)])

That’s all folks! We will look at sets in the next tutorial.

Report Error/ Suggestion

Related Posts:

CopyRight © 2020

CopyRight © 2020