How To Access Dictionary In Python – 5 Easy Ways (Updated Guide for 2022)

In this guide, we will show you everything you need to know about how to access dictionary in python, so keep reading!

Below you can find out 5 different methods to access dictionary in python,

Method 1 – Python Tutorial For Beginners 5: Dictionaries – Working With Key-Value Pairs

Hey there hows it going everybody in this video well be learning about dictionaries and how we can work with. Them and python so dictionaries allow us to work with key value pairs and if youre coming from another programming. Language then you may have heard these called hash maps or associative arrays so when i say that well be. Working with key value pairs these are two linked values where the key is a unique identifier where we can.

Find our data and the value is that data so we can actually think of that almost like a real. Physical dictionary where we look up for definitions so in that example each word that we look up would be. The key and the definition of that word would be the value so lets go ahead and take a look. At some examples so lets say that we wanted to represent a student using a dictionary so to do this. We could just create a student variable and set this equal to these curly braces and thats how we start.

Our dictionary now within our curly braces here we will first put in our key so lets say that we. Want a key of name now were going to put in a colon to separate our key from our value. And for the name here well just start off with john and now lets add some more keys and values. And to separate these keys and values were going to put in a comma so next lets put in a. Key of age and a value of 25 and lastly well put in a key of courses and for this.

Value well pass in a list of courses here so well say math and comp sci so now lets print. Out our student and see how that looks so if we save that and run it and we can see. That it prints out all of our keys and values now lets just get a value of one key so. To do this we can add square brackets after our dictionary and then specify the key that we want to. Access so i can put in square brackets here and lets say that we want to access the name of.

That student dictionary so ill just pass in the name key and run that and we can see that that. Gave us that value of that name key now if i wanted the courses instead then i could just pass. In that courses for the key if i run that then you can see that we got this list of. Math and comp sign so we can see that these values and our dictionary can be just about anything our. Name is a string our age is an integer and the courses are list now all of our keys are.

Currently strings but they can actually be any immutable data type so usually these would there be strings or injures. But there are a few more data types that they can be as well so for example instead of name. As our key here if for some reason we wanted this to be an integer so ill just pass in. One so a 1 is a valid key and now if i access that key of 1 and run that. And you can see that that gave us john but im gonna set that back to be a string for.

Now and keep that as name so what happens if we try to access a key that doesnt exist so. For example ill try to access the key of phone for a phone number so if we run this then. We can see that we get a key error because that phone key doesnt exist now throwing an error when. A key doesnt exist might not always be what we want so sometimes we might just want to return none. Or a default value so to do this we can use the dictionaries get method so instead of accessing this.

Key this way if we were instead to say not get and use the get method so lets just go. Ahead and get the name since we know that that key already exists so if i run that then we. Could see that that works just like before and gave us the value of john but if i try to. Access a key that doesnt exist so well try to access that phone key again if i save that and. Run it then by default this get method returns none instead of an error and we can also specify a.

Default value for keys that dont exist so to do this we can just pass the default value that we. Want as a second argument to this get method so ill just put in a comma here and well put. In a string that just says not found so if i save that and run it now we can see. That four keys that dont exist it returns not found okay so lets look at how we can add a. New entry to our dictionary so lets say that we wanted to add that phone number to our student dictionary.

And well set this just above our print statement here so to do this its just as easy as saying. Student and then we will set the key that we want to set and set this equal to and well. Just set this equal to a string of five five five five five five five if i save that and. Run it then we can see that it found that value of the phone key when we ran our print. Statement now if a key already exists if we set its value like this then it will update the value.

Of that key so for example if right below this i was to say student and name is equal to. And well just pass in jane if i save that and then a print out ill comment out that for. Now if i print out our entire student variable then we can see down here that the value for name. Was updated when we assigned it to jane now we can also update values using the update method now this. Is especially useful when we want to update multiple values at a time so for example lets say that we.

Wanted to add this phone number update this name and also update the age as well so to do this. All in one shot we could say student not update and this takes in a dictionary as an argument and. The dictionary is just everything that we either want to add or update so we can say that we want. To update that name to jane and we will update the age to lets say 26 and we also want. To add this phone key and that phone key will just set as what we had before five five five.

Five five five five now if i save that and run it and we can see that just by running. This one statement we updated the name to jane the age is now 26 and it has this new key. Of phone number okay so now lets say that we wanted to delete a specific key and its value now. One way that we can do this is by using the del keyword which stands for delete so let me. Just remove these updates here and then we can say so lets say that we wanted to delete the students.

Age so its as easy as just saying it del student age and now if we run this then we. Can see that now the only keys that exist are named and courses so that age key was deleted now. Another way that we can remove a key and value is with the pop method so if we remember from. Our video on lists the pop method will remove but also return and that value so that allows us to. Grab the removed value with a variable so we could say age is equal to and do a student not.

Pop and what we want to pop is that age so if i save that then well also print the. Age here below student if i run that and we can see that the age and value were removed from. Our dictionary but we also created that age variable that contained the value that we popped off so that popped. Off 25 okay now lets look at how we can loop through all the keys and values of our dictionary. So first if we want to see how many keys we have in our dictionary that we can just print.

Out its length with the elian function so if i was to say print le n of student and run. That then we can see that it returns 3 because we have 3 keys and our student dictionary now if. We wanted to see all of these keys then we could just print out student dot keys if i run. That then we can see that that gave us all of the keys of our dictionary if we wanted all. Of our values then we could print out student not values if i run that you can see that that.

Gives us only two values now if we wanted to see the keys and values then we could use this. Items method if i run this then we can see that now we have these pairs of key and value. Pairs so we have name john age 25 courses with the list and well be coming back to these pairs. In just one second so if we wanted to loop through all of the keys and values in our dictionary. We might be tempted to loop through the same way we loop through our list but if we just loop.

Through our list without using any method then itll just loop through the keys so for example if you were. To say four key in student and then print out that key if we run this then we can see. That it just looped through and printed out all of those keys now in order to loop through the keys. And values well need to use that items method that we just saw a second ago and so well just. Plug that in there well say student items and now these come and a pair of two values so instead.

Of just key were also going to have to access the value so we can say four key value and. Stu not items and now well print out the key and that value so if i run that so we. Can see that each loop through this key variable was equal to each key and this value variable was equal. To each value okay so i think thats going to do it for this video i hope that now everyone. Feels comfortable working with dictionaries and the functionality thats available to us and in the next video well be going.

Over conditionals and how to write if-else and elif statements well also be learning more about boolean and boolean operators. Now if anyone has any questions about what we covered in this video then feel free to ask in the. Comment section below and ill do my best to answer those and if you enjoy these tutorials and would like. To support them then there are several ways you can do that the easiest way is to simply like the. Video and give it a thumbs up and also its a huge help to share these videos with anyone who.

You think would find them useful and if you have the means you can contribute through patreon and theres a. Link to that page in the description section below be sure to subscribe for future videos and thank you all. For watching you.

Method 2 – Python – Accessing Nested Dictionary Keys

Welcome to another pyfrom video in this video well have a look at how we can access information in nested. Dictionaries for that we need nested data and this is the data we will use for the purpose as you. Can see this is data in json format so well also learn how we can access well information stored in. The json format in python and the data is extracted from the q&a section of our angular 7 course on.

Udemy because students can ask questions and normally they will get answers for that we have some results right here. Because we retrieve this data from an api and we can see that we have a question right here this. One from the angular course as i said and we also got replies inside the replies we can see that. The reply is the class answer and we got a user and this user has a name the display name. Right here in that case its max now the same thing right here we have another question we have replies.

We have the first reply again from max and we got another reply from danielle right here by the way. Not the real name of the student now and this goes on a bit right here down there with some. Other students and in the end what i want to achieve right here in python is i want to create. A list and save this list in json format which includes all these names right here so i want to. Have a list of all the people who answer questions in our q&a thread right here in the angular course.

As i said just an excerpt though so thats what we want to do in this video so lets get. Started to get started you need two things you need – and you need a trip return notebook running we. Talked about that in another video and the second thing you need is you need a folder in here not. A test folder that was just for well testing purposes but you need the source folder and inside the source. Folder you should put this source data json file you can find a link to that file below in the.

Video description then navigate back to the main folder so the folder where you save the state at hume and. Create a new – free notebook right here you can give it any name you want lets call it may. Be nested dict like that now what i first want to do is i want to access the information stored. In that file for that and only me to do one thing i must import the json encoder for python. And this is pretty simple because you only have to type import jason like that if you now hit shift.

And enter well you can get started because now we can use the functionality of this chasen encoder – well. Open this chase and file for that we simply type with open like that and now we open brackets and. Add single quotation marks because now we have to specify either the file name of the file that you want. To open this is true in case the file is stored in the same folder wherever you are currently working. In in our case we store the file in the source folder so what we have to do right now.

Is we have to add dot slash because we want to start well navigating starting from our current position and. Then we add the name of the folder which is source and now the name of the file which is. Source data dot jason like that so now we want to open this file stored in that folder and we. Have to give this a name which could be access jason for example and then we have to add a. Colon right here because now we said that we want to open that file but we didnt tell python what.

You want to do with that information in this file for that we simply enter maybe read content you can. Give it any name of your choice right here and read content should be you what well it should be. Equal to something that turns this json data into a so-called python object because python by default cannot work with. Jason beta with fraud jason data you could say it needs to have a structure which it understands a so-called. – object in the end and for the purpose so to turn this jason data into a so-called – object.

We can now use our jason encoder once again that we imported right here because by typing jason dot load. Right here we simply tell – to turn this file and the content of this file so of our source. Data jason into a python object well have a closer look at that in a few seconds and by that. Make it readable for python and this also allows us to access the content in the end now with jason. Load we simply have to add in brackets the name that we defined right here so access jason access jason.

Like that if we now it shift and enter you can see well nothing basically but entering the name of. Our variable right here and hitting shift and enter basically shows us the content of our adjacent file now as. We turned it into a python object now what type of a python object do we actually have right here. Well if you add type in front of your variable like this and like that and hit shift and enter. You can see that we are working with a so called dictionary here i will not dive into the details.

About dictionaries in this video make sure to have a look at the link that you can find in the. Video description though but generally we can access information stored in dictionaries by accessing the so-called key in the dictionary. Now this sounds a little bit strange now lets maybe delete the type right here and the bracket and display. The results so what im referring to basically is that this curly brace is right here indicate that we have. A dictionary in python and that this dictionary basically contains this single key right here we have more information in.

Here that follows after that right here and right there up to here but all this information is the so-called. Value of this dictionary so to summarize that we have the results key right here now dictionary and the value. Which contains this list more about lists or how we can access tight end lists in a few seconds now. In python if it would refer to this key right here we would also be able to display the corresponding. Value of that key and thats exactly what we want because remember in the end my goal is to create.

A list of all the display name values right here so of the key display name which contains the value. Of the person who gave an answer to a question right here so for that we simply use our variable. Right here once again so read content read content and now enter square brackets and now we only have to. Add single quotation marks and refer to the key which contains the values that you want to display in our. Case this is the results key right here so if we enter results now like this and hit shift and.

Enter we can see that we now display the entire value that our results key contains now lets maybe also. Give this material name maybe question access because thats to basically have right here and hit shift and enter once. Again and if we now enter type question access once again like this you can see that the type of. Our data changed because as i said previously we had a dictionary now we access the values of this dictionary. And the values that this dictionary contains are not dictionaries or something like that or single values it is a.

Single value but a special signal value its a list right here so lets maybe get rid of our type. Once again and have a look at the result so this list right here in – also as for the. Dictionary more about lists can be found in the video description the list right here we have is well indicated. By this square brackets right here and ending right there and this is basically now the enteric content that we. Have in our list the problem with this list is that we cannot access list items the way we did.

It before for the dictionary so if i would write something like question access like this open curly the square. Brackets and maybe access i dont know the course right here which could be in here so lets say course. Then this is not working because as our error mesh message shows right here list indices must be integers or. Slices not strings i dont know dive into slices now but we could use an integer for example so we. Could enter something like 1 right here and then we would access the list item with the index 1 and.

Surprisingly the list item with the index 1 if you maybe keep that name right here in mind so the. List item with the index 1 its not this one right here right but its the second one that one. Right here daniel weed why because accessing list items starts with a number of 0 for the first item so. Appear and then if you want to access the second one you will enter an index of 1 and so. On so if i would change this right here to 0 like that then we would access indeed our first.

List item which we have up here so max but there so these are basically our list items as you. Can see right here our list items again our dictionaries and now you can also see why this video is. About accessing nested dictionaries because we basically have a dictionary which contains a list which contains a dictionary which again. Then contains a list and so on so thats this nesting structure we talk about in this video now the. Thing is that with this logic right here we can access a single list item but actually we want to.

Access all our list items right here now if we want to kind of repeat something to get all the. Results a for loop might be something useful here for that we can get rid of that and we simply. Enter 4 because this indicates that we want to such a loop right here now we can give this a. Name so here we could call this maybe question data something like that you can name this as you prefer. The important thing is that you then add in and in what well in our question access because we basically.

Want to retrieve the information we have in our list right here so for that we enter in question access. Like this and now we simply print our question data that we defined right here so lets see what the. Result will look like and as you can see the result looks quite good because now we were able to. Access the information in our list have a look at the square bracket at the square bracket which are gone. Now and now we can basically display the actual content but surprisingly as you can see if i enter type.

Question data so up here the type of that information we have in our loop if i enter that oops. Not like that if i enter type question data you can see we have a dictionary once again but thats. Actually one of the core things already that i want to talk about in this video we learned how we. Can access dictionaries and how we can access lists and as we have both kind of nested into each other. We cannot use the information we learned previously and access our information in our dictionary remember we can now access.

A specific key in our dictionary to retrieve the value now which keys do we have in our dictionary well. We basically have the class key the question not the question the course key then we have another dictionary right. Here and then we have the replies key now why dont we access the replies key and see what values. This key contains little spoiler it should be this list right here but well see so lets now enter maybe. Replies access to all the gift is a name because now we finally access our replies and we can access.

This replies by enter question data which we previously defined now again the square brackets and now enter replies adhere. Because this is what we want to access lets shift and enter and type replies access once again and as. You can see we now printed our replies right here well actually we didnt because we printed our replies so. We can access the replies key or the value the replies key contains but we printed this one right here. So the last reply because what – basically thats before our logic is it basically has a look at all.

The information it has and returns the last matching information so the last matching here that we have right here. Will have a look at how you can resolve this in a few seconds but for the moment we are. Able to access our replies which is quite cool the problem is that if i enter type once again like. This and like that we have a list once again but with our new knowledge we cannot simply add another. For loop to access the information in our replies for that we type 4 and now maybe i dont know.

How our previous naming was question data so thats maybe call it replies data then as i said youre totally. Free here so for replies data in replies access youre not free here you have to use the name right. Here that you gave to this variable support applies data in replies access please print our replies data so lets. See whats inside there basically and as you can see well no big surprise our replies access contains another dictionary. So basically this dictionary right here well actually we have three dictionaries to be more precise here now we almost.

Finished our primary goal we are almost able to access the display name right here but for that we again. Have to access a specific here for dictionary to retrieve the corresponding value now for that lets maybe call this. User name now because we can now simply say that we want to access replys data appear so our result. Of the for-loop open the square brackets and now access user well actually if think back about what we just. Learned we will access the last user here so this one so we can enter user oops like that but.

As we have a dictionary well nested inside of another dictionary we cannot simply add the square brackets once again. And now simply refer to the key that we want to access in this nested dictionary specifically in our case. This is the display name key right here so if i enter display name now like that and hit shift. And enter and type username once again like this then you can see that we finally made it we are. Not able to access for all these nested dictionaries and lists our display name of next right here so this.

Last name so that is the basic process how you can access these nested information at this nested data we. Have two problems though at the moment we only return one result so the display name right here the last. One and actually my goal was to access to information retrieve all the display names so all the names of. People who answered questions in our course and then basically save this list to a new json file lets take. Care of that fact that we only get back one result at the moment because we actually have all the.

Need right here which has need to you well put it into another structure a different structure which in our. Case could be a function in python now lets write this function and see how this works writing a function. Simply works with def right here now we have to define a function name maybe get user names something like. That then we add the brackets which wont contain anything in our case right here and now we add the. Colon and now this function will not be built from scratch because we actually have all the information we need.

Which has have to combine it in a function to make sure this function runs our loops again and again. Up until it found all the relevant information that we need so what this means for us is up until. It found all the this plain name keys and returned all the corresponding values now to get started we have. To scroll up a little bit up to here right there this is the first thing we need because what. We basically want to do is we want to first open our file and read the content and after that.

We want to run our function thats the logic thats why i dont include this part right here in our. Function but as soon as we open our file we want to run our function and then this function should. Give us back the values of the results key right here in our dictionary so lets paste this right here. So with the access to the values of the results key we can scroll up once again im not up. To here up to here now because now we can take the for loop without the print statement because we.

Dont need to print our data now we only need to for loop so we basically go down right here. And paste this right there because what youre saying here is that please access the value and once you access. The value with question access right here please give me back all the list items we have inside this list. Because remember question access is of type list we can see this right here you can see it its a. List so we got our for loop and this for loop returns question data and question data again is a.

Dictionary so we can now simply copy this part right here after all for loop because the for loop was. Running so it basically says well please give me back all the information in our list and then please give. Me access to the values that we have for our replies key right here in our question data thats what. We have right here so we are almost there and now we simply use our last for loop this one. Right here and paste it right there because now we simply want to say okay please give me back all.

The list items that we have in our replies access right here so basically all the list items in here. And then finally just give me back the username with this code right there so as you can see we. Basically just summarize the information that we created previously before the code put it into function and also made sure. That with this for loops now integrated in this function that we will not only retrieve back one single result. So not only one single name right .

Conclusion – How To Access Dictionary In Python

The purpose of this post is to assist people who wish to learn more about the following – accessing dictionary using for loop in python || part-57 || python tutorial for beginners, python training nested dictionary in python, python dictionaries || python tutorial || learn python programming, python dictionaries tutorial 3 | how to access nested dictionaries, #17: python dictionaries to store key, dictionary in python, python dictionaries & for loops (beginner’s guide to python lesson 8), access dictionary items in python || part-52 || python tutorial for beginners, #traversingadictionary python programs | traversing a dictionary | functions & methods, how to iterate through a dictionary in python, dictionary in python (create, add, remove, access, list, loop, check, merge) – python for beginners, dictionaries in python – advanced python 03 – programming tutorial, python 3 – episode 10 – dictionary, indexed with keys, python dictionary tutorial 19 | python dictionary method get to efficiently access dictionary data, simple python coder – file text into python dictionary.

Thank you for visiting Softwarediscover.com and reading this article! If you found this article useful, feel free to share it with your friends and help spread knowledge.