Dictionaries – Basics and Methods

Introduction

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-

my_dict={'a':1,'b':2,'c':3}
print(my_dict['a'],my_dict['b'],my_dict['c'])

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 –

my_dict['d']=4

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-

my_dict.pop('b')
print(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.

my_dict['a']=12
print(my_dict)

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-

print(len(my_dict))

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-

True
False

Methods

keys() method

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

print(my_dict.keys())

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.

print(my_dict.values())

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.

print(my_dict.items())

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.

Dictionaries – Basics and Methods