“What is Dictionary” and How to use Dict{} in python !

Hello, welcome back. And today we’re going to be learning more about Python dictionaries and nesting. And by the end of today, you will have built a program with use dictonery. “What is Dictionary” and How to use Dict{} in python !

“What is Dictionary”

Hello, welcome back. And today we’re going to be learning more about Python dictionaries and nesting. And by the end of today, you will have built a program with use dictionary.

So All Right.

So the first thing I want to talk about is dictionaries in Python. Now, dictionaries in Python work kind of similarly to dictionaries in real life, right? So if you were to look up a word in the dictionary say the word code, then you might find the definition as something along the lines of program instructions for the computer. And dictionaries are really useful because they allow us to group together and tag related pieces of information.

The way I like to think about dictionaries is in the form of a table. Every dictionary has two parts to it

Key Value
Apple a round fruit with shiny red or green skin that is fairly hard and white inside
Mango a tropical fruit with smooth yellow or red skin, that is soft and orange inside with a large seed
Banana a long curved fruit with a thick yellow skin and that is soft inside, which grows on trees in hot countries

On the left hand side is the key,and that is the equivalent of the word in the dictionary, and then it’s also got an associated value. That would be the equivalent of the actual definition of the word.

Now let’s say that we took this variation simple table of definitions of programming words that we’ve come across so far and we go ahead and we try to convert it right into a dictionary,
how would we do that?

Let me firstly

drop the last two rows and let’s just start with the first one.

Key Value
Apple a round fruit with shiny red or green skin that is fairly hard and white inside


The first thing we want to do is we want them to create a dictionary. And to do that in Python, this is what the syntax looks like:
                                      {key:value}

We have a set of curly braces and everything that’s inside the curly brace is the content of our dictionary. The key goes first followed by a colon and then followed by the value. In our table we’ve got this word “apple”, which is the first key,

so we can replace that over here in our dictionary.
{“apple”:value}

 

And the value that’s associated with this key is the definition for a “Apple”. So a round fruit with shiny red or green skin that is fairly hard and white inside,
that becomes the value and can be replaced here after the colon.

{“apple”:” a round fruit with shiny red or green skin that is fairly hard and white inside “}

So now, we’ve created an actual dictionary using Python code.
What if you wanted to have more than one entry in your dictionary?

Well,
you would separate each of the key value pairs using a comma,

fruits_dictionary = {
“apple”:” a round fruit with shiny red or green skin that is fairly hard and white inside”,
“mango”:”a tropical fruit with smooth yellow or red skin, that is soft and orange inside with a large seed”,
“banana”:”a long curved fruit with a thick yellow skin and that is soft inside, which grows on trees in hot countries”,
}

and then you can continue adding key and value pairs until you get to the end of your dictionary. All right,
let’s take a look at dictionaries in action.
We create a dictionary and I’ve store it inside of a variable call Fruits Dictionary. Now,

fruits_dictionary = {
“apple”:” a round fruit with shiny red or green skin that is fairly hard and white inside”,
“mango”:”a tropical fruit with smooth yellow or red skin, that is soft and orange inside with a large seed”,
}

currently I’ve only got two entries in this dictionary, the definition for a apple and the definition for a mango. Now,

the first thing I want to highlight is when you create a dictionary that has more than one element such as in this case,and format properly so that its more easily redable.

the last curly brace should go at the very beginning in line with the start of the dictionary. And another thing that’s quite nice to do is to cap off all entries in your dictionary or list with a comma. This means that if you needed to add more items into the dictionary you can simply just hit enter and continue typing the next thing. And if we wanted to add another entry, it’s a simple as adding in the key, a colon and then the value and to cap it.

fruits_dictionary = {
“apple”:” a round fruit with shiny red or green skin that is fairly hard and white inside”,
“mango”:”a tropical fruit with smooth yellow or red skin, that is soft and orange inside with a large seed”,
“banana”:”a long curved fruit with a thick yellow skin and that is soft inside, which grows on trees in hot countries”,
}

So now our dictionary represents exactly the same data as we saw in our table over here with a bunch of key value pairs and a total of three entries.
Now,
the next thing I want to do is what if I wanted to retrieve an item from the dictionary, because we know that if we had a lists
lists[]
what we would do is we would use a set of square brackets and then we would give the index of the item that we wanted. So the item at index zero or one or two and so on and so forth.
Now for dictionaries, it’s kind of similar in terms of syntax but the only difference is that dictionaries have elements which are identified by their key.
If we wanted this piece of information, for example,
then all we have to do is tap into the dictionary and then add a set of square
fruits_dictionary[“”]

brackets and inside the square brackets, we’re going to provide the key. so here the key is a string and it’s the string “apple”.
So let’s go ahead and put apple in here.
fruits_dictionary[“apple”]
And now if I go ahead and print this, then you can see that it is going to give me the value, which is ‘round fruit with shiny red or green skin that is fairly hard and white inside’

print(fruits_dictionary[“apple”])
Output:-
a round fruit with shiny red or green skin that is fairly hard and white inside

Now it’s really really important that you make sure that when you’re fetching something out of a dictionary by it’s key that you actually spell the key correctly.A really really common error is when you’re trying to retrieve something out of a dictionary and you’ve just made a very simple typo. So instead of ‘l’ I’m typing ‘i’ here and you’ll see we get an error. And the error tells us that it’s a key error referring to this particular key and it highlights this line 7 where we’re trying to retrieve

print(fruits_dictionary[“appie”])

Error

Traceback (most recent call last):
File “main.py”, line 7, in
print(fruits_dictionary[“appie”])
KeyError: ‘appie’

something out of this dictionary by this key.
Basically it’s telling you that this key doesn’t actually exist and it can’t be found. So it doesn’t know what it is that you want. Remember how when we had lists and when we try to retrieve something that was not inside the list.

[“a”,”b”,”c”][4]
So for example, this particular list at index 4 doesn’t actually exist because this is zero one, two, three, and four is actually not a piece of data inside of this list. Similarly with dictionaries, if we try to put in a key that doesn’t exist, then we get this key error.
Now another common pitfall that students fall down into is they don’t actually
print(fruits_dictionary[mango])
use the correct data type. So for example,

Without string
fruits_dictionary = {
apple:” a round fruit with shiny red or green skin that is fairly hard and white inside”,
mango:”a tropical fruit with smooth yellow or red skin, that is soft and orange inside with a large seed”,
banana:”a long curved fruit with a thick yellow skin and that is soft inside, which grows on trees in hot countries”,
}

if we defined this dictionary without putting a string around each of these key, then it’s going to error out and it won’t even let us run. It’s going to tell us undefined named apple because it thinks that this is a
apple = “a apple”
variable that you’ve declared somewhere,
but it’s not. In fact, what you wanted are these strings for keys.

With String
fruits_dictionary = {
“apple”:” a round fruit with shiny red or green skin that is fairly hard and white inside”,
“mango”:”a tropical fruit with smooth yellow or red skin, that is soft and orange inside with a large seed”,
“banana”:”a long curved fruit with a thick yellow skin and that is soft inside, which grows on trees in hot countries”,
}

And so when you have a key that is a string, when you’re trying to retrieve the data from that key, you also have to make sure that you provide the key in its actual data type.
print(fruits_dictionary[“mango”])
So for example, if this was just a number, say 789,

fruits_dictionary = {
“apple”:” a round fruit with shiny red or green skin that is fairly hard and white inside”,
789:”a tropical fruit with smooth yellow or red skin, that is soft and orange inside with a large seed”,
“banana”:”a long curved fruit with a thick yellow skin and that is soft inside, which grows on trees in hot countries”,
}

then, of course, all you have to write in here is just 789, and it would know that this piece of data is what you wanted.
So that’s how you retrieve items from a dictionary by adding a square bracket and then giving it the key.
And it will look for the key inside the dictionary and give you back the value.

fruits_dictionary = {
“apple”:” a round fruit with shiny red or green skin that is fairly hard and white inside”,
“Mango”:”a tropical fruit with smooth yellow or red skin, that is soft and orange inside with a large seed”,
}

Now, what if you wanted to add a piece of data such as that banana that we had earlier on, but you want to do it programmatically. So instead of doing it
when you were defining the dictionary at the beginning, what if at some later stage in your program you needed to add a new entry?
Well, to do this, it’s also really simple. All you have to do is to tap into the dictionary, which is called fruits_dictionary []
in our case and again, using square brackets, we define the key.
The key I’m going to add is our “banana”.

fruits_dictionary [“banana”] = “a long curved fruit with a thick yellow skin and that is soft inside, which grows on trees in hot countries”

and then after a equal sign, I get to assign the value. So in my case, the value is going to be the definition for a “banana”. And now when this line of code is executed and we go ahead and just print the fruits_dictonary after this has happened,

fruits_dictionary = {
“apple”:” a round fruit with shiny red or green skin that is fairly hard and white inside”,
“mango”:”a tropical fruit with smooth yellow or red skin, that is soft and orange inside with a large seed”,
}
fruits_dictionary[“banana”] = “a long curved fruit with a thick yellow skin and that is soft inside, which grows on trees in hot countries”
print(fruits_dictionary)
Output:-
{‘apple’: ‘ a round fruit with shiny red or green skin that is fairly hard and white inside’, ‘mango’: ‘a tropical fruit with smooth yellow or red skin, that is soft and orange inside with a large seed’,
‘banana’: ‘a long curved fruit with a thick yellow skin and that is soft inside, which grows on trees in hot countries’}

So let’s hit run and you can see that previously we had a fruits_dictionary that had only two items, “apple” and “mango”.
And after this where we print our fruits_dictionary again, you can see it’s now got three items, “apple”,”mango”, “banana”.
Now very often when you’re writing code, it can be really helpful to start out with a empty dictionary. Just as you saw previously,
empty_list = []
you create an empty list by simply having a set of square brackets with nothing inside.
You can also create an empty dictionary by simply creating a set of curly braces with nothing inside. And then at a later stage,
empty_dict = {}  
you can add to your dictionary by using this method that you saw here

empty_dict[]

fruits_dictionary[“banana”] = “a long curved fruit with a thick yellow skin and that is soft inside, which grows on trees in hot countries”

Now, on the other hand, you might actually want to wipe an entire dictionary. Here,I’m creating a new empty dictionary by creating this pair of curly braces with nothing inside.
empty_dict = {}
But I can also wipe an existing dictionary by simply doing the same thing. We know that this dictionary, fruits_dictionary, has three items in it.but I’m going to say fruits_dictionary equals empty dictionary

empty_dict = {}
fruits_dictionary = {}
print(fruits_dictionary)

And now if I move this print statement down here, then you can see that when it prints out, it’s actually going to be completely empty.

empty_dict = {}
fruits_dictionary = {}
print(fruits_dictionary)
Output:-
{}

That can be really useful if you wanted to clear out a user’s progress or for example, if a game restarts, then all the scores and stats will probably have to be wiped empty. So this is one way that you could do that.
Now this method of tapping into a dictionary,
using the key to fetch the relevant item from it and then doing something with it goes beyond just adding. You can also use this to edit an item in a dictionary.
fruits_dictionary[“apple”] =
I’m going to fetch the item that has a key of bug, and I’m going to redefine its value. So currently it should be an error in a program that prevents the program from running as expected. And I can prove that if I just wrap this around a print statement. If instead I wanted this to be a different value, then I can simply use the same syntax as I did for adding new items but in this case I’m actually editing this entry because it’s going to look through the dictionary, find a value with this key and then assign it to whatever I put on the right hand side of the equal sign. Now, on the other hand, if it finds nothing with that key, then it’s going to create a new entry with the value again on the right hand side of the equal sign.
Now let’s say that a “apple” is instead ‘A Apple is good for health.’
Now, if I go and print my programming dictionary once more,

fruits_dictionary = {
“apple”:” a round fruit with shiny red or green skin that is fairly hard and white inside”,
“mango”:”a tropical fruit with smooth yellow or red skin, that is soft and orange inside with a large seed”,
}
fruits_dictionary[“banana”] = “a long curved fruit with a thick yellow skin and that is soft inside, which grows on trees in hot countries”
fruits_dictionary[“apple”] = “Apple is good for health.”
print(fruits_dictionary)

Output:-
{‘apple’: ‘Apple is good for health.’, ‘mango’: ‘a tropical fruit with smooth yellow or red skin, that is soft and orange inside with a large seed’, ‘banana’: ‘a long curved fruit with a thick yellow skin and that is soft inside, which grows on trees in hot countries’}

then you can see that the definition for our bug has now just been changed. The final thing with regards to dictionaries that I think is really, really useful is how you loop through a dictionary. And using your knowledge from lists you might think that to loop through a dictionary, you would, let’s say we are using a for loop. And we say for, thing in fruits_dictionary,

for fruit in fruits_dictionary:
print(fruit)

let’s go ahead and print this thing each time.
what do you think will be printed?
when I click run,

for fruit in fruits_dictionary:
print(fruit)

Output:-
Apple
Mango
Orange

All right
I thought it would give me each of the items in the dictionary with this key and its value. But instead this code actually just gives you the keys.
Now, of course, once you do have access to the key, instead of fruit,I should actually really say for key in fruits_dictionary. If I wanted to print the key, then of course I could just write print key. But if I wanted to get hold of the value, I could equally just as easily tap into my dictionary, use the square brackets and pass in that key. So now when I hit run, you can see it’s giving me first

for key in fruits_dictionary:
print(key)
print(fruits_dictionary[key])

Output:-
apple
Apple is good for health.
mango
a tropical fruit with smooth yellow or red skin, that is soft and orange inside with a large seed
banana
a long curved fruit with a thick yellow skin and that is soft inside, which grows on trees in hot countries

the key from this line and then secondly the value based on this line. I’m using that retrieval code in order to get the value.
Of course, remember that you can get access to all the code that I’m writing here by looking at the end code of the day that you’ll find on the course resources list.
we do a program that will really solidify everything you’ve learned in this lesson so far.

PROGRAM -1 (Define Desiganation behalf of salary)

office_salary = {
“Atul”:20000,
“shakti”:15500,
“sumit”:16200,
“avitesh”:10500,
“pappu”:10000,
}

desigantion = {}

for key in office_salary:
salary = office_salary[key]
if salary >= 20000:
desigantion[key] = “MANAGER”
elif salary > 15000:
desigantion[key] = “MIS”
elif salary > 10000:
desigantion[key] = “DATA OPERATOR”
else:
desigantion[key] = “OFFICE BOY”
print(desigantion)

Output:-
{‘Atul’: ‘MANAGER’, ‘shakti’: ‘MIS’, ‘sumit’: ‘MIS’, ‘avitesh’: ‘DATA OPERATOR’, ‘pappu’: ‘OFFICE BOY’}

Nesting Lists and Dictionaries

Now that we’ve seen lists as well as dictionaries I want to talk about a concept that you often see in both of these collection types and that’s something called nesting. Now, if we imagine a list or a dictionary being something like a folder where lots of things can be stored inside it, then nesting lists and dictionaries is just a matter of putting one inside the other.
For example,
here a dictionary that is very simple,
{key: value}
it’s only got one key-value pair. Now we know that we can add multiple key-value pairs
{
key: value,
key2: value2
}

into the same dictionary by just adding a bunch of commas to separate them. Now, what if instead of having a simple value like a string or a number,
I could also put a list as a value as well. Similarly,
{
key: [list],
key2: {dict}
}

I could also use a dictionary as a value. In this case we’ve got a list as the value for key, this first one, and we’ve got a dictionary as the value for key2. Notice how this is a list and a dictionary nested inside another dictionary.
The structure gets a little bit more complex, but it gives us more flexibility when we’re trying to store more complex pieces of data.
Coming back to our code,
let’s go ahead and create some sample dictionaries to see what this actually looks like in real life.
For example,

famous_place = {
“Delhi”:”Red Fort”,
“Agra”:”Taj Mahal”,
}

if I wanted to nest a list in a dictionary, then I would be able to represent even more complex data.
For example,
if I had a travel log where I was going to collect a dictionary of all the places I had been for each of the countri I’ve traveled to. So for example

this is Wrong way to show your dictionery into list
travel = {
“Delhi”:”red fort”, “chandani chowk”,”india gate”
}

if I had traveled to Delhi and I wanted to say that I’ve been to multiple places, I can’t simply just say red fort, and then chandani chowk, india gate, that doesn’t really work because each key can only have one value. The only way that we can make these three pieces of data one value is by turning it into a list, like so.

this is right way to show your dictionary into list
travel = {
“Delhi”:[“red fort”, “chandani chowk”,”india gate”]
}

So now in our travel log dictionary as represented by the curly braces, we have one key value pair and it just so happens that the value in this case is a list. And of course you can go on and add as many entries as you would like

travel = {
“Delhi”:[“red fort”, “chandani chowk”,”india gate”],
“Agra”:[“Taj Mahal”,”Fatehpur Sikri”, “Agra fort”],
}

and still preserving this kind of structure of key being a string and the value being a list.
Now, this idea of nesting isn’t limited dictionaries by the way. You could also just nest a list in a list. So you could have a list which is A and then B, and then the third item just happens to be another list which has C and D.
[“A”, ”B”, [“C”, “D”]]
This is perfectly valid Python code but it’s not quite as useful as nesting a list in a dictionary or a dictionary in a dictionary, because the way that data is structured.
Now, what if you wanted to nest a dictionary in a dictionary?
Let’s say that we wanted to expand our travel log. And instead of just storing the places that I visited in each state,what if I wanted to also keep track of how many visits I’ve made to that cities? Or what if I wanted to actually label what this piece of data is? Because at the moment it’s kind of like here’s a bunch of places that’s associated with the cities.
All right, so here’s the solution. By nesting a dictionary
we can label the red fort, chandani chowk and india gate lists as places visited. All I need to do is create the string,

travel = {
“Delhi”:{“places_visited”:[“red fort”, “chandani chowk”,”india gate”]},
“Agra”:[“Taj Mahal”,”Fatehpur Sikri”, “Agra fort”],
}

“places_visited” and add a colon after it. But there’s one more step. We have to add a pair of curly braces so that delhi is associated with a single value, namely our nested dictionary.
Now that we have a dictionary of the travel log, all the cities I’ve been to, and each country has a value that is a dictionary in itself and it can store multiple pieces of data including the places I’ve visited in that cities as well as things such as the total number of visits, which in this case would have a string as the key and a number of as the value.

travel = {
“Delhi”:{“places_visited”:[“red fort”, “chandani chowk”,”india gate”], “total_visits”: 10},
“Agra”:[“Taj Mahal”,”Fatehpur Sikri”, “Agra fort”],
}

Now have a go at creating your own travel log or modifying the second part of the travel log so that you also have a dictionary nested in a dictionary and you’re able to represent something like this,
the number of places you visited in a list and another additional piece of data,

travel = {
“Delhi”:{“places_visited”:[“red fort”, “chandani chowk”,”india gate”], “total_visits”: 10},
“Agra”:{“places_visited”: [“Taj Mahal”,”Fatehpur Sikri”, “Agra fort”], “total_visits”:5},
}

if you wanted to. And so now our data structure is such that we’ve got a list nested inside a dictionary, which is in itself nested in another dictionary.
Now that we’ve seen nesting lists inside dictionaries, dictionaries inside dictionaries, the last thing I want to show you is nesting a dictionary inside a list.
[{key: [value],
key2: {dict},
},
{
key: value,
key2: value,
}]

So we could basically have multiple dictionaries inside a single list. So remember that lists are ordered and they’re accessed by the positions inside the list. So this dictionary would be the item at index zero, this one at index one and so on and so forth Whereas inside a dictionary, the items are accessed by their keys like this delhi or agra
Now I want to do the last type which is nesting a dictionaryin a list .

travel = {
“Delhi”:{“places_visited”:[“red fort”, “chandani chowk”,”india gate”], “total_visits”: 10},
“Agra”:{“places_visited”: [“Taj Mahal”,”Fatehpur Sikri”, “Agra fort”], “total_visits”:5},
}

And I’m going to be working with the same travel log that we had previously, but I want to change it so that instead of having this being one giant dictionary with key-value pairs, I want to change it so that each of these entries are a dictionary in itself.
Instead of having delhi be the key of this dictionary here, I want the turn it into its own key-value pair. Going inside this dictionary, I’m going to create a new key which is called cities and then put delhi

travel = {
{“cities”:”Delhi”,”places_visited”:[“red fort”, “chandani chowk”,”india gate”], “total_visits”: 10},
{“cities”:”Agra”,”places_visited”: [“Taj Mahal”,”Fatehpur Sikri”, “Agra fort”], “total_visits”:5},
}

as the value for that key. So now I have an entire dictionary that has three pieces of data. The cities visited, the place_visited, and the total number of visits.
So now you can see we’ve got two dictionaries and instead of holding these two dictionaries inside a dictionary, I’m going to change it so that it’s now a list. I’m going to turn these curly braces into square brackets

travel = [
{“cities”:”Delhi”,”places_visited”:[“red fort”, “chandani chowk”,”india gate”], “total_visits”: 10},
{“cities”:”Agra”,”places_visited”: [“Taj Mahal”,”Fatehpur Sikri”, “Agra fort”], “total_visits”:5},
]

and this way we can add as many of these dictionaries inside the list and iterate through them if we need to. When we’ve been creating dictionaries that only have one or two key-value pairs, we’ve kind of just kept it all on one line. But once you’ve got more and more key-value pairs in the dictionary, it’s usually a good idea to go ahead and separate out each of the entries,

travel = [
{
“cities”:”Delhi”,
“places_visited”:[“red fort”, “chandani chowk”,”india gate”],
“total_visits”: 10
},
{
“cities”:”Agra”,
“places_visited”: [“Taj Mahal”,”Fatehpur Sikri”, “Agra fort”],
“total_visits”:5
},
]

Like what I’m doing here.
now it’s a little bit easier to see that we have a list which contains two items, and each item is a dictionary. Each dictionary has three key-value pairs and they all contain different types. of data. The first one has a value which is a string, the second one holds a list and the third one holds a number. The data types inside a dictionary can be completely mixed up if you want it to. But what can’t change is you still need a key and a value separated by a colon.
Now the only downside to this is you want to make sure that you’re actually aware that later on when you try to pull out the number of visits, it’s actually a number that you’re working with rather than a string or when you’re trying to get hold of the cities visited it’s a list rather than a dictionary, for example.
So now that we’ve the various different types of nesting, it’s time for you to actually really understand this and get to grips with this concept by completing lesson .
I’ve got a program for you based on this travel log and you’ll need to use what you’ve learned so far to be able to complete it.

PROGRAM-2 (use Dictionary in list for no. of visit places)

travel = [
{
“cities”:”Delhi”,
“places_visit”:[“red fort”, “chandani chowk”,”india gate”],
“total_visits”: 10
},
{
“cities”:”Agra”,
“places_visit”: [“Taj Mahal”,”Fatehpur Sikri”, “Agra fort”],
“total_visit”:5
},
]

def add_new_cities(cities_visited, total_visited, places_visited):
new_cities = {}
new_cities[“cities”] = cities_visited
new_cities[“places_visit”] = places_visited
new_cities[“total_visit”] = total_visited
travel.append(new_cities)
add_new_cities(“Mumbai”,2, [“Taj hotel”, “Khandala”])

print(travel)

Output:-
[{‘cities’: ‘Delhi’, ‘places_visit’: [‘red fort’, ‘chandani chowk’, ‘india gate’], ‘total_visits’: 10}, {‘cities’: ‘Agra’, ‘places_visit’: [‘Taj Mahal’, ‘Fatehpur Sikri’, ‘Agra fort’], ‘total_visit’: 5}, {‘cities’: ‘Mumbai’, ‘places_visit’: [‘Taj hotel’, ‘Khandala’], ‘total_visit’: 2}]

So, Today You will learned “What is Dictionary” and How to use Dict{} in python ! with example a program.

Thank you ❤️

Check out https://www.devopscheetah.com/how-to-use-def-function-in-python/

Leave a Reply

Your email address will not be published. Required fields are marked *