Join us and get access to hundreds of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to hundreds of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Hint: You can adjust the default video playback speed in your account settings.
Hint: You can set the default subtitles language in your account settings.
Sorry! Looks like there’s an issue with video playback 🙁 This might be due to a temporary outage or because of a configuration issue with your browser. Please see our video player troubleshooting guide to resolve the issue.

Operators and Methods for Dictionaries in Python

Give Feedback

Dictionaries have some of the same operators and built-in functions that can be used with strings, lists, and tuples. For example, the in and not in operators return True or False according to whether the specified operand occurs as a key in the dictionary.

You can use the in operator together with short-circuit evaluation to avoid raising an error when trying to access a key that is not in the dictionary. The len() function returns the number of key-value pairs in a dictionary.

Now that you’ve completed this course, you can test your knowledge with this quiz:

00:00 Operators and methods. As you start to work with dictionaries, you’ll want to manipulate them using operators and built-in functions, or methods. These serve to extend the functionality of dictionaries and they allow you to work with them in creative ways.

00:17 In the console, we’ll run through a bunch of examples. It won’t be an exhaustive look at all the operators and methods available to work with dictionaries—that would take hours, maybe even days—but this will be plenty to get you started on your quest to become the dictionary master. So, let’s hop into the console.

00:36 All right. We’ve got our dictionary of bad_guys from earlier. Go ahead and rebuild that if you’ve restarted your console or something. A couple of great operators to use with dictionaries are the in and not in operators, and you can use these to check for the existence of keys in a dictionary.

00:56 So we know 'deadpool' is in there, right? So if you do 'deadpool' in bad_guys, we get a Boolean value.

01:07 This is great, using in and not in operators to check for the existence of keys before pushing new key-value pairs into your dictionary so you don’t clobber existing ones.

01:18 Another good use for these operators is to avoid raising an error when trying to access a key that is not in the dictionary. Remember, in our earlier example,

01:31 we threw an error when we tried to call 'green arrow'. If we had done it this way with our checking with the in operator type of functionality, we just would have got a Boolean False.

01:45 So if we’d set up an expression, something like this—checking first before we did something that could potentially lead to an exception—we will get what’s called a short circuit.

01:59 This is where Python only checks this first part of the expression and short circuits because it got a False Boolean value and did not run the rest of the expression.

02:09 Another way to check for the existence of keys is with the built-in function called .get(). If a key exists, it’ll simply return the value. If it does not exist,

02:30 it’ll return nothing. It’s actually returning null, or None, if you print it. Another useful builtin is the .items() function, which returns a list of the key-value pairs.

02:50 This is useful for throwing into a list, which puts your key-value pairs into tuple form so you can then work with them like you would any list and index them.

03:04 So if I do it like this, list(dictionary.items()), this puts them in a regular list—oops. This will put them into a regular list form, and now we can index.

03:20 You can see it’s actually returning a list of tuples and we can call them with index numbers. This is also useful for iterating. You could do something like this.

03:33 If I call that list() again…

03:42 Maybe we just want to print the values or something. And what we’re doing is for each tuple that is in that list that we built using the bad_guys dictionary, with the built-in .items() function right here, we’re going to print the tuple, but only the value—so the second position in that tuple. It’ll look like that.

04:07 Likewise, also useful ways to iterate: .keys() or .values(). Each dictionary has the built-in .keys() and .values() operator.

04:19 It looks like this for .keys(), and that just gives you the keys. And same for .values(). Also helpful for iterating.

04:33 Another great builtin is .pop(), and you can remove a key from a dictionary, and this completely removes the key and returns its value. So 'deadpool' should be gone from bad_guys. And a similar but more random function is .popitem(), which will pull a random key-value pair from the dictionary and return it as a tuple.

05:05 So now 'batman' is gone, and we’re left with just 'daredevil'. There can only be one. Let’s make a couple new dictionaries for this next example.

05:19 Dictionary one will contain "Robin" and "Galahad".

05:28 In our second one, we’re going to put three items in there.

05:45 Man, I can’t spell today! "Black Knight". One of those days.

05:54 Finally, our "Shrubbery". Close the dictionary, and this is a super important built-in function to know: .update(). It can be used to update values and add key-value pairs to the dictionary with tuples or keyword arguments. And that looks like this. Go ahead and try it.

06:18 We’re going to update the value for c and change it from 'Rabbit' to 'Ni' and then let’s change the value for d, which was 'Shrubbery', to 'Green Knight'.

06:38 Let’s see what happened there. Awesome! Another handy feature for .update() is you can use it to merge dictionaries. So these two dictionaries you just made, let’s try to merge them.

06:56 We’re going to merge d2 into d1. If the key exists—actually let’s list both of these again one more time. d1 and d2.

07:11 If the key exists—which we know 'b' exists in both dictionaries—its value will be updated. If the key does not exist, the key-value pair will be added.

07:26 So check this out. d1.update(d2). And now we’ve got a merged dictionary where 'b', 'Black Knight', from d2 overwrote 'Galahad', and then 'c' was added for 'Ni', and d was added containing 'Green Knight'.

07:51 And last but not least, the .clear() builtin empties all key-value pairs. So, there are a bunch of these built-in functions, and I highly suggest now that you’re on your way to mastering Python dictionaries to go read their documentation.

08:12 If we went over every single builtin, this course would be two hours long easily. And they’re not all necessarily useful, but going through the documentation will get you used to that and it’ll also give you some great ideas for using dictionaries in your own programming. So that’s it for the course. In this course, we went over the basics of what is a dictionary, we incrementally built out a dictionary using the social media profile idea, we went over the restrictions on keys and values, and we covered common operators and methods. Well, that’s all I have.

08:48 Thank you so much for joining me. Any questions or concerns, please leave a comment and I’ll get back to you as soon as possible. Have a great day!

Wiggers on July 30, 2019

Very well presented and shows I am not the only one who can’t type and spell!

ALXTheMaster on July 31, 2019

Great course!

leesmith4044 on Aug. 2, 2019

What method[s] do you suggest for creating a large dict from a file?

herma48852 on Aug. 2, 2019

Excellent presentation!

Anonymous on Aug. 3, 2019

Cool thanks..

Sergio on Aug. 4, 2019

Would be nice to have included methods to mass load a dictionary (e.g. from a JSON file) or save dictionary values… Nevertheless, it was fine! Thanks!

justchris86 on Aug. 7, 2019

Love it! this is basically an API call isn’t it?

muralichintapalli on Aug. 10, 2019

It would be really helpful to have real world example of Dict and also to build dictionaries from some file

Daniel on Aug. 13, 2019

Great course.

muthu raja on Aug. 14, 2019

Reading/Importing JSON data as dicitionary.

import json

jsonData = '[{"FirstName" : "Bob", "LastName" : "Johnson"}, {"FirstName": "Andrew", "LastName" : "Brown"}]'

# if you want to parse JSON file, use json.load() function instead
parsedJson = (json.loads(jsonData)) 

"""
parsedJson is stored as list
# whereas, each item within parsedJson list is stored as dictionary
"""
print(parsedJson)
print(type(parsedJson)) 
#print(type(parsedJson[0])) 

#Reading values from list, and then fetch FirstName, LastName from dictionaries
for x in parsedJson:
    print(x["FirstName"], x["LastName"])

Dibsdalec on Aug. 20, 2019

The get method has None as default, this default can be changed.

Would be nice to discuss collections, DefaultDict, in Collections used to avoid key errors if you try and query a key that does not exist.

Jean Ferreira on Sept. 1, 2019

Thanks for the videos.

Pygator on Sept. 14, 2019

Excellent coverage of the basics of Dicts in Python. An advanced course with projects using them would be equally great.

sideproject8 on Dec. 17, 2019

Out of all the video instructors so far I enjoy your style the best. Calm, chill, takes time to explain things, and enjoyable to listen to. Props you to my man, I hope more comes from you.

JulianV on Dec. 19, 2019

Thanks Paul. Nice!

Paulo Szewierenko on March 16, 2020

Objective and direct! Very useful!

sweir12525 on June 22, 2020

You raced over restrictions so fast I had not idea what you meant.

Konstantin Schukin on July 2, 2020

Thank you for great course!

Ben Nduwuba on July 2, 2020

Superb course , thanks Paul

paolotagliente on July 27, 2020

thanks Paul.....enough to make me going nicely....this is a great base really.....

Ghani on Oct. 19, 2020

A very informative course; thank you so much!

deewright on Dec. 22, 2020

Very well explained, thanks.

Arturo on Jan. 4, 2021

From Python version 3.6 the .popitem() method is no longer a random function but simply returns and removes the last key:value pair in the dictionary. This is explained in another RP tutorial about dictionaries.

Become a Member to join the conversation.