[Part VII]Dictionaries in Python🐍

[Part VII]Dictionaries in Python🐍

Welcome back to the series "Learn Python with me!"👋👋

Last time we learned about a widely used data structure in Python called List. Let's move on further into the world of data structures and get started with Dictionaries in Python.

Dictionaries reminded me of a story. We had an English teacher in 5th grade who insisted that we learn 5 words from the fat blue-colored hard-bound📘 Oxford Dictionary every day. She would then pick a random student and ask for its detailed meaning and correct pronunciation.

Those classes soon became a nightmare, and the whole affair lasted for only two months😂.

Although they would have benefitted us had we continued.....🤔

Let's leave the past where it is and come to the topic of Dictionaries.

What are Dictionaries?

Dictionaries are built-in Python🐍 data structures that associate or map keys to values.

A key is a unique identifier. A value is something that we associate with the key.

In the case of the Dictionary, the keys are the words, and the values are the meanings of the words.

In the case of the Phonebook, the keys are the names, and the values are the phone numbers.

Creating a Dictionary in Python

  • They start and end with curly braces {}.

  • The key: value pairs are separated by a colon(;).

  • Each pair is separated by a comma.

student_roll = {'Harry':1, 'Hermione':2, 'Ron':3}

Accessing Elements in a Dictionary

print(student_roll['Harry'])

The output should be 1.

access_dict.gif

Note: We can access a value by its key and not the other way round.

To check whether a particular key is present in the dictionary or not, we can use the in keyword. It returns a boolean value(i.e True or False)

check_dict.gif

Let's create a dictionary from scratch and then start using certain built-in functions to see what they do.

As you would have guessed by now, my examples always revolve around Harry Potter🧙‍♂️ or Star Wars🌠 or Avengers🤟.

Let's divert and bring in some Pixar characters here😁.

pixar = {} #this is an empty dictionary 

#We are going to add key:value pairs
#Let's map some Pixar characters to their movie release date

pixar['Woody'] = 1995
pixar['Mike'] = 2001
pixar['Nemo'] = 2003
pixar['Jack-Jack'] = 2004
pixar['WALL-E'] = 2008
pixar['Coco'] = 2017
pixar['Ian'] = 2020
pixar['Luca'] = 2021

Now, that we have our dictionary, let's look at some functions that we can use.

dict.get(key)

This function returns the corresponding value associated with the key.

print(pixar.get('Mike'))

The output will be 2001

It returns None if the key is not present in the given dictionary.

Another, variation of this is dict.get(key,default)

It displays the default value mentioned in case the key does not exist in the dictionary.

print(pixar.get('Joy'),100)

It gives an output of 100

dict.keys()

It is similar to a range of keys in a dictionary. It returns a view object containing the keys.

A view object is a dynamic view object, in simple words, the object will reflect any changes made to the dictionary.

We use this to loop over keys in a dictionary.

for key in pixar.keys():
    print("We met "+key+" in "+str(pixar[key]))

Output:

We met Woody in 1995
We met Mike in 2001     
We met Nemo in 2003     
We met Jack-Jack in 2004
We met WALL-E in 2008   
We met Coco in 2017     
We met Ian in 2020      
We met Luca in 2021

dict.values()

It is similar to a range of values in a dictionary. We can loop over the values like this👇

for values in pixar.values():
    print(values)

Output:

1995
2001
2003
2004
2008
2017
2020
2021

len(dict)

We can get the number of keys/values in a dictionary with the help of the len() function

In this case, len(pixar) would give 8 as the output.

dict.pop(key) and del dict[key]

You might want to remove certain key/value pairs from the dictionary. You can do that by using pop() or del

Let's use both of them and see the difference

pop&del in dict.gif

  • When I use pop(), it returns the value of the key that is being deleted.
  • When I use del, it does not return anything.

Hence, we can use pop when we want the value to be returned, or else we can use del.

dict.clear()

Now, if we want to clear every element from the list we can use the clear() function.

clear.gif

There we go, we managed to return to a clean slate again.😁

This is all about Dictionaries in Python!! See you next time!

Happy Learning!!