Python Tutorial - Dictionary Method Complete Guide

Python Exercise Lists

We know that the data type of a Python dictionary is dict, and we can use dir (dict) to see which methods the type contains, for example:


Among methods, the usage of fromkeys and get method has been introduced in the Python Dictionary so I won't go into details here, this section only introduces the remaining methods.

Python Keys, Values, And Items Methods

These three methods are introduced together because they are all used to get specific data in the dictionary:

  • keys method is used to return all the keys in the dictionary;
  • values method is used to return the values corresponding to all the keys in the dictionary;
  • items method return all key-value pairs in the dictionary.

Consider the following example:

age = {'Jason': 95, 'Nicole': 29, 'Harry': 10}
print (age.keys())
print (age.values())
print (age.items())

The output is:

dict_keys(['Jason', 'Nicole', 'Harry'])
dict_values([95, 29, 10])
dict_items([('Jason', 95), ('Nicole', 29), ('Harry', 10)])

It can be seen that the types of keys, values, and items return values are dict_keys, dict_values, and dict_items.

It should be noted that in Python 3.x, their return value is not our common list or tuple type, because Python 3.x does not want users to directly manipulate the return values of these methods.

If you want to use the data returned by these three methods in Python 3.x, there are generally two scenarios:

a) Use the list function to convert the data they return into a list, for example:

age = {'Jason': 95, 'Nicole': 29, 'Harry': 10}
b = list (age.keys())
print (b)

The output is:

['Jason', 'Nicole', 'Harry']

b) Use a for in loop to iterate through their return values, for example:

age = {'Jason': 95, 'Nicole': 29, 'Harry': 10}
for i in age.keys ():
    print (i, end = '')
print ("\ n ---------------")
for j in age.values ():
    print (j, end = '')
print ("\ n ---------------")
for i, j in age.items ():
    print ("key:", i, "value:", j)

The output is:

JasonNicoleHarry\ n ---------------
952910\ n ---------------
key: Jason value: 95
key: Nicole value: 29
key: Harry value: 10

Python Copy Method

The copy method returns a copy of a dictionary, that is, a new dictionary with the same key-value pairs, for example:

scores = {'Jason': 95, 'Nicole': 99, 'Harry': [80, 77]}
b = scores.copy ()
print (b)

The output is:

{'Jason': 95, 'Nicole': 99, 'Harry': [80, 77]}

As you can see, the copy method copies all the data in dictionary a to dictionary b.

Note that the copy principle followed by the copy method includes both deep and shallow copies. Take the copy dictionary scores as an example, the copy method will only make a deep copy of the top-level key-value pairs, that is, it will apply for another memory to store {'Jason': 95, 'Nicole': 99, 'Harry': []}; for some list type values, this method makes a shallow copy of it, that is, the value of [80, 77] in b is not unique, It is shared with scores.

Consider the following example:

a = scores = {'Jason': 95, 'Nicole': 99, 'Harry': [80, 77]}
b = scores.copy()
#Add new key-value pairs to scores. Since b has already copied all key-value pairs of scores in advance, adding new key-value pairs to scores will not affect b.
scores ['Peter'] = 100
print (scores)
print (b)
#Because b and scores share [80, 77] (shallow copy), removing elements from the list in scores will also affect b.
scores['Harry']. remove (80)
print (a)
print (b)

The output is:

{'Jason': 95, 'Nicole': 99, 'Harry': [80, 77], 'Peter': 100}
{'Jason': 95, 'Nicole': 99, 'Harry': [80, 77]}
{'Jason': 95, 'Nicole': 99, 'Harry': [77], 'Peter': 100}
{'Jason': 95, 'Nicole': 99, 'Harry': [77]}

It is not difficult to see from the running results that adding a new key-value pair to scores does not change b; while modifying the elements in the list of a key-value pair of scores, b also changes accordingly.

Python Update Method

The update method can use the dictionary's key-value pairs to update an existing dictionary.

When executing the update method, if the updated dictionary already contains the corresponding key-value pair, the original value will be overwritten; if the updated dictionary does not contain the corresponding key-value pair, the key-value pair is added in.

Look at the following code:

age = {'Jason': 35, 'Nicole': 19, 'Harry': 80}
age.update ({'Nicole': 45, 'Peter': 10})
print (age)

The output is:

{'Jason': 35, 'Nicole': 45, 'Harry': 80, 'Peter': 10}

It can be seen from the running results that because the updated dictionary already contains a key-value pair with the key "Nicole", the value of the key-value pair will be rewritten when the update is made; the updated dictionary does not contain the key with "Peter" ", So a new key-value pair will be added to the original dictionary when updating.

Python Pop and Popitem Methods

Both pop and popitem are used to delete the key-value pairs in the dictionary. The difference is that pop is used to delete the specified key-value pair, and popitem is used to randomly delete a key-value pair. Their syntax format is as follows:

dictname.pop (key)

Where dictname represents the dictionary name and key represents the key. The following code shows the usage of two functions:

age = {'Jason': 35, 'Nicole': 19, 'Harry': 80, 'Peter': 56, 'Mark': 88, 'Kevin': 50}
print (age)
age.pop ('Peter')
print (age)
age.popitem ()
print (age)

The output is:

{'Jason': 35, 'Nicole': 19, 'Harry': 80, 'Peter': 56, 'Mark': 88, 'Kevin': 50}
{'Jason': 35, 'Nicole': 19, 'Harry': 80, 'Mark': 88, 'Kevin': 50}
{'Jason': 35, 'Nicole': 19, 'Harry': 80, 'Mark': 88}

Python Description of Popitem

In fact, it is inaccurate to say that popitem method randomly deletes a key-value pair in the dictionary. Although the dictionary is a kind of unnecessary list, the key-value pair is also stored in the bottom layer. The last key-value, which is similar to the list's pop method, implements the "pop" operation in the data structure.

Python Setdefault Method

The setdefault method is used to return the value corresponding to a key, and its syntax is as follows:

dictname.setdefault (key, defaultvalue)


  • dictname represents the name of the dictionary,
  • key represents the key,
  • defaultvalue represents the default value (you can leave it alone or None if you don't write it).

When the specified key does not exist, setdefault method will first set a default defaultvalue for this non-existent key, and then return the defaultvalue.

In other words, the setdefault method always returns the value corresponding to the specified key:

  • If the key exists, the value corresponding to the key is directly returned;
  • If the key does not exist, then set the default default value for the key, and then return the default value corresponding to the key.

Look at the following code:

age = {'Jason': 35, 'Nicole': 19, 'Harry': 80}
print (age)
#key does not exist, specify the default value
age.setdefault ('Peter', 64)
print (age)
#key does not exist, does not specify a default value
age.setdefault ('Mark')
print (age)
#key exists, specify the default
age.setdefault ( 'Nicole', 20)
print (age)

The output is:

{'Jason': 35, 'Nicole': 19, 'Harry': 80}
{'Jason': 35, 'Nicole': 19, 'Harry': 80, 'Peter': 64}
{'Jason': 35, 'Nicole': 19, 'Harry': 80, 'Peter': 64, 'Mark': None}
{'Jason': 35, 'Nicole': 19, 'Harry': 80, 'Peter': 64, 'Mark': None}


More Tutorials:

Python Installation - Linux (Ubuntu)
Python Installation - Mac OS
Integrated Development Environment - IDE
Python - Basic Variables
Python - Sequence Introduction
Python - Output Formatting
Python - Escape Character
Python - Type Conversion
Python - Numbers
Python – Arithmetic Operators
Python – Assignment Operators
Python – Comparison Operators
Python – Logical Operators
Python – Precedence and Associativity Operators
Python – Bytes Type and Usage
Python – Long & Raw Strings
Python – Concatenate Function
Python – Slice Function
Python – Length and Split Function
Python – Join and Count Function
Python – Find Function
Python – Index Function
Python – Alignment Function
Python – Startswith and Endswith Function
Python – String Case Conversion
Python – Remove Specified Character
Python – Encode and Decode Function
Python – dir and help Function
Python – Input Output Introduction
Python – Basic Operation
Python – Open Function
Python – Read Function
Python – Readline Function
Python – Write Function
Python – Close Function
Python – Seek and Tell Function
Python – Pickle Module
Python - File Input Module and Linecache Module
Python - Pathlib Module
Python - Pathlib Module
Python - os.path Module
Python - fnmatch Module
Python - Tuple Introduction
Python - List Introduction
Python - List Add Element
Python - List Delete Element
Python - List Modification Element
Python - List Find Element
Python - Dictionary Introduction
Python - Dictionary Basic Operation
Python - Dictionary Method Guide
Python - Set Collection
Python - Set Basic Operation
Python - Set Basic Method
Python - Frozenset Method
Python - If Condition I
Python - If Condition II
Python - While loop
Python - For loop
Python - Pass Statement
Python - Break Statement
Python - Zip Reverse Function
Python - Function Introduction
Python - Positional Parameters
Python - Key Arguments
Python - None and Return
Python - Variable Scope
Python - Local Function
Python - Closure Method
Python - Lamdba Expression

More Python Exercises:

Python String Exercises
Python List Exercises
Python Library Exercises
Python Sets Exercises
Python Array Exercises
Python Condition Statement Exercises