Locked learning resources

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

Unlock This Lesson

Locked learning resources

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

Unlock This Lesson

Operators and Methods for Dictionaries in Python

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.

To learn more about dictionaries, you might want to check out Python Basics: Dictionaries.

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

Take the Quiz: Test your knowledge with our interactive “Python Dictionaries” quiz. You’ll receive a score upon completion to help you track your learning progress:


Interactive Quiz

Python Dictionaries

Test your understanding of Python dictionaries

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!

Avatar image for Wiggers

Wiggers on July 30, 2019

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

Avatar image for ALXTheMaster

ALXTheMaster on July 31, 2019

Great course!

Avatar image for leesmith4044

leesmith4044 on Aug. 2, 2019

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

Avatar image for herma48852

herma48852 on Aug. 2, 2019

Excellent presentation!

Avatar image for Anonymous

Anonymous on Aug. 3, 2019

Cool thanks..

Avatar image for Sergio

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!

Avatar image for justchris86

justchris86 on Aug. 7, 2019

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

Avatar image for muralichintapalli

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

Avatar image for Daniel

Daniel on Aug. 13, 2019

Great course.

Avatar image for muthu raja

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"])
Avatar image for Dibsdalec

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.

Avatar image for Jean Ferreira

Jean Ferreira on Sept. 1, 2019

Thanks for the videos.

Avatar image for Pygator

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.

Avatar image for sideproject8

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.

Avatar image for JulianV

JulianV on Dec. 19, 2019

Thanks Paul. Nice!

Avatar image for Paulo Szewierenko

Paulo Szewierenko on March 16, 2020

Objective and direct! Very useful!

Avatar image for sweir12525

sweir12525 on June 22, 2020

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

Avatar image for Konstantin Schukin

Konstantin Schukin on July 2, 2020

Thank you for great course!

Avatar image for Ben Nduwuba

Ben Nduwuba on July 2, 2020

Superb course , thanks Paul

Avatar image for paolotagliente

paolotagliente on July 27, 2020

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

Avatar image for Ghani

Ghani on Oct. 19, 2020

A very informative course; thank you so much!

Avatar image for deewright

deewright on Dec. 22, 2020

Very well explained, thanks.

Avatar image for Arturo

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.

Avatar image for DoubleA

DoubleA on Feb. 1, 2021

I think the .get() method returns a value and not a key as mentioned in the video. If the given key exists, its value is returned and if not then the default value.

my_dict = {'a': 1, 'b':2, 'c':3}
print(my_dict.get('d', 'No such key exists')

The method when invoked will thus return:

No such key exists

since there’s no ‘d’ key in the above dictionary.

Avatar image for jacquesd

jacquesd on March 3, 2021

Hello. After watching all the videos about iterating through dictionary, I couldn’t find one that shows how to iterate where ‘values’ are list with multiple strings in them… Like this kind of thing:

scene = { "objects": [], "camera": ['camera1'], "lights": ['light1', 'light2', 'light3']  }

I’m a beginner so I can’t really figure out how to go through all these “Keys” and then loop through all the “values” list and extract them.

Cheers,

Jacques.

Avatar image for Bartosz Zaczyński

Bartosz Zaczyński RP Team on March 4, 2021

@jacquesd One way to do that would involve using two nested for loops:

>>> scene = {
...     "objects": [],
...     "cameras": ["camera1"],
...     "lights": ["light1", "light2", "light3"]
... }
>>> 
>>> for component, values in scene.items():
...     print(component.upper())
...     for value in values:
...         print(" -", value)
... 
OBJECTS
CAMERAS
 - camera1
LIGHTS
 - light1
 - light2
 - light3
Avatar image for jacquesd

jacquesd on March 4, 2021

Thank you very much Bartosz! I knew the logic but couldn’t figure out how to implement it.

Cheers,

Jacques.

Avatar image for h-dzeba

h-dzeba on Nov. 18, 2021

What is the difference between bad_guys.items() and list(bad_guys.items())? In the video, the insturctor says that .items() will return a list of key-value pairs. If that’s so, then why do we need to list the list to turn the key-value pairs into tuples?

Avatar image for Bartosz Zaczyński

Bartosz Zaczyński RP Team on Nov. 18, 2021

@h-dzeba Bad guys are a Python dictionary:

>>> bad_guys = {
...     "daredevil": "kingpin",
...     "batman": "bane",
...     "deadpool": "evil dead pool"
... }

Calling .items() on them will return a list-like dict_items object comprised of key-value pairs:

>>> bad_guys.items()
dict_items([('daredevil', 'kingpin'), ('batman', 'bane'), ('deadpool', 'evil dea
d pool')])

Since this object is an iterable, there’s no difference whether you use it directly in a for-loop or convert it to a plain old list first:

>>> list(bad_guys.items())
[('daredevil', 'kingpin'), ('batman', 'bane'), ('deadpool', 'evil dead pool')]
Avatar image for Enzo Maria Savelli

Enzo Maria Savelli on Sept. 13, 2024

When trying to apply the update built in function, i’m give a syntax error. d.update(3 = ‘nemico’,) SyntaxError: expression cannot contain assignment, perhaps you meant “==”? What am I doing wrong?

Become a Member to join the conversation.