Public account: You and the cabin by: Peter Editor: Peter

Hello, I’m Peter

Python’s three data types, strings, lists, and tuples, are all ordered data types.

This article introduces an unordered Python data type: dictionary. Dictionaries are mainly used to store mapped data.

The article directories

The dictionary features

Dictionaries are a data type that is often used in Python. Dictionaries can store data of any data type, and the data stored can be modified, just like lists. Each basic element of a dictionary contains two parts: the key and its corresponding value, value.

  • Keys and values are separated by colons (all symbols involved are in English)
  • Each pair of elements is separated by a comma
  • The entire data is enclosed in braces

{“name”:” xiaoming “,”age”:22,”sex”:” male “}

In dictionaries, keys are different, repetitive, immutable data types, and values can be of any data type. Tuples are immutable, so they serve as dictionary keys. Lists are mutable and cannot be used as dictionary keys. Keys only support immutable data types

Dictionaries are out of order, so they may be printed in a different order each time.

Dictionary creation

Dictionaries can be created in two ways:

  • Use curly braces{}create
  • Created using the dict function

When using curly braces {} to create a dictionary, the curly braces must contain multiple key-value pairs separated by colons. Multiple key-value pairs are separated by commas (,).

Creating an empty dictionary

dic1 = dict(a)# empty dictionary
dic1
Copy the code
{}
Copy the code
type(dic1)  # check type
Copy the code
dict
Copy the code
dic2 = {}   # curly braces to create
dic2
Copy the code
{}
Copy the code
type(dic2)
Copy the code
dict
Copy the code

Curly braces: Only one key-value pair

dic3 = {"name":"Xiao Ming"}
dic3
Copy the code
{'name': 'xiaoming '}Copy the code
type(dic3)
Copy the code
dict
Copy the code

Curly braces: Multiple key-value pairs

The key must be a string, and the value can be any type of data, such as: string, number, list, etc

dic4 = {"name":"Xiao Ming".# string
        "age":25.# numerical
        89:111."sex":"Male".# string
        "score": [100.98.99]   # list
       }
dic4
Copy the code
{' name ':' xiao Ming ', 'age: 25, 89, 111,' sex ':' male ', 'score' : [100, 98, 99]}Copy the code
type(dic4)
Copy the code
dict
Copy the code

Dict functions: multiple key-value pairs

# tuples are stored in the list
data1 = [("name"."Xiao Ming"),
         ("age".25),
         ("score"[100.99.98])
        ]  

dic5 = dict(data1)
dic5
Copy the code
{'name': 'score': [100, 99, 98]}Copy the code
# nested lists within lists

data2 = [["name"."Xiao Ming"],
         ["age".25],
         ["score"[100.99.98]]
        ]  

dic6 = dict(data2)
dic6
Copy the code
{'name': 'score': [100, 99, 98]}Copy the code

Dict function: created by specifying keyword arguments

You can also create a dictionary by specifying a keyword argument for dict, in which case the dictionary key does not allow expressions

dic7 = dict(name="Xiao Ming",age=25,sex="Male")  # name is not in quotes
dic7
Copy the code
{'name': 'xiaoming ', 'age': 25, 'sex':' male '}Copy the code
type(dic7)
Copy the code
dict
Copy the code

Dict function: created by zip function

data3 = zip(("name"."age"."sex"), ("Xiao Ming".25."Male"))

data3
Copy the code
<zip at 0x1122e2870>
Copy the code
dict8 = dict(data3)
dict8
Copy the code
{'name': 'xiaoming ', 'age': 25, 'sex':' male '}Copy the code

The dictionary operation

Keys are the key data in the dictionary, and all values are accessed by their own keys, so we must master each key-based operation.

  • Access value through key
  • Add key-value pairs by key
  • Delete key-value pairs by key
  • Modify key-value pairs by key
  • Checks whether the specified key-value pair exists

Operation 1: Access value through key

The following code shows how to access the corresponding value by key

dic5
Copy the code
{'name': 'score': [100, 99, 98]}Copy the code
dic5["name"]
Copy the code
'Ming'Copy the code
dic5["score"]
Copy the code
[100, 99, 98]
Copy the code

If the key does not exist, an error is raised:

dic5["sex"]
Copy the code
---------------------------------------------------------------------------

KeyError                                  Traceback (most recent call last)

<ipython-input-18-8c2513616156> in <module>
----> 1 dic5["sex"]


KeyError: 'sex'
Copy the code

Operation 2: Add a key-value pair

dic5  # before
Copy the code
{'name': 'score': [100, 99, 98]}Copy the code
dic5["address"] = Shenzhen city, Guangdong Province  # add key-value pairs
dic5  After the #
Copy the code
{' name ':' xiao Ming ', 'age: 25,' score ': [100, 99, 98],' address ':' the guangdong province shenzhen '}Copy the code

Add a new key-value pair

dic5["birth"] = "1993-08-01"

dic5
Copy the code
{' name ':' xiao Ming ', 'age: 25,' score ': [100, 99, 98],' address ':' 'shenzhen city, guangdong province,' birth ':' 1993-08-01 '}Copy the code

Operation 3: Delete key-value pairs

dic6
Copy the code
{'name': 'score': [100, 99, 98]}Copy the code
# 1. Delete

del dic6["name"]
Copy the code
dic6  
Copy the code
{'age': 25, 'score': [100, 99, 98]}
Copy the code

We find that the name key-value pair is missing and has been deleted

del dic6["score"]   
Copy the code
dic6
Copy the code
{'age': 25}
Copy the code

When deleted again, the score pair is also gone

Operation 4: Modify key/value pairs

To modify a key value pair, the value in a key is modified. The newly assigned value overwrites the original value.

dic5
Copy the code
{' name ':' xiao Ming ', 'age: 25,' score ': [100, 99, 98],' address ':' 'shenzhen city, guangdong province,' birth ':' 1993-08-01 '}Copy the code
# 1 change name
dic5["name"] = "Little red"  

dic5
Copy the code
{' name ':' red ', 'age: 25,' score ': [100, 99, 98],' address ':' 'shenzhen city, guangdong province,' birth ':' 1993-08-01 '}Copy the code
dic5["name"] + "From" + dic5["address"]
Copy the code
'Xiao Hong is from Shenzhen, Guangdong Province'Copy the code
# 2. Change the date

dic5["birth"] = "1993-08-08"
dic5
Copy the code
{' name ':' red ', 'age: 25,' score ': [100, 99, 98],' address ':' 'shenzhen city, guangdong province,' birth ':' 1993-08-08 '}Copy the code

Operation 5: Check whether a key-value pair exists

If you want to determine whether the dictionary contains a specified key, you can use the IN or not in operators. It should be noted that both of these operators are judged based on dictionary keys

dic5
Copy the code
{' name ':' red ', 'age: 25,' score ': [100, 99, 98],' address ':' 'shenzhen city, guangdong province,' birth ':' 1993-08-08 '}Copy the code
"sex" in dic5  
Copy the code
False
Copy the code
"sex" not in dic5   
Copy the code
True
Copy the code
  • Above: Sex is not in dic5 and the result is False:
  • The following: name name in the dictionary DIC5, the result is True.
"name" in dic5
Copy the code
True
Copy the code

Summary of dictionary operations

Using the above example, we compare the index of a list with that of a dictionary:

  • The key is the key in the dictionary, which is equivalent to the dictionary index, but the index is not necessarily an integer.
  • Dictionary keys are any immutable data type: numeric, string, tuple, and so on
  • Indexes in a list are always incremented from 0; However, if the keys in the dictionary are all integers, they may not start at 0 and not be consecutive
  • Indexes that do not exist cannot be assigned in the list. Dictionaries allow assignment of keys that do not exist, which is like adding a key-value pair

The dictionary method

Dictionaries in Python are represented by the dict class, and you can use dir(dict) to see what methods that class contains

View dictionary methods

print(dir(dict))  # Check the method of dictionary pairs
Copy the code
['__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']
Copy the code

Dictionary method 1: Clear ()

Use to clear all key-value pairs in a dictionary. A dictionary becomes an empty dictionary after the clear() method is executed.

dic7   # performed before
Copy the code
{'name': 'xiaoming ', 'age': 25, 'sex':' male '}Copy the code
dic7.clear()  # to perform
Copy the code
dic7  Empty dictionary after execution
Copy the code
{}
Copy the code

Dictionary method 2: get()

The method is to get the value from the key. The dictionary raises an error when we use the square bracket syntax to access a key that doesn’t exist. If the get method is used, None is returned.

dic5
Copy the code
{' name ':' red ', 'age: 25,' score ': [100, 99, 98],' address ':' 'shenzhen city, guangdong province,' birth ':' 1993-08-08 '}Copy the code
print(dic5.get("name"))  # Access existing keys
Copy the code
The little redCopy the code
print(dic5.get("birth"))
Copy the code
1993-08-08
Copy the code

The following sex key does not exist, but instead of reporting an error, prints None:

print(dic5.get("sex"))  
Copy the code
None
Copy the code

Error if curly braces are used:

dic5["sex"]
Copy the code
---------------------------------------------------------------------------

KeyError                                  Traceback (most recent call last)

<ipython-input-43-8c2513616156> in <module>
----> 1 dic5["sex"]


KeyError: 'sex'
Copy the code

Dictionary method 3: Update

  • If a key exists, it is used to update the value of key-value pairs in the dictionary.
  • If the key-value pair does not exist, it is added to the dictionary:
dic5
Copy the code
{' name ':' red ', 'age: 25,' score ': [100, 99, 98],' address ':' 'shenzhen city, guangdong province,' birth ':' 1993-08-08 '}Copy the code
dic5.update({"name":"Xiao Ming"})  Update the existing key
Copy the code
dic5
Copy the code
{' name ':' xiao Ming ', 'age: 25,' score ': [100, 99, 98],' address ':' 'shenzhen city, guangdong province,' birth ':' 1993-08-08 '}Copy the code
dic5.update({"sex":"Male"})   If the # key does not exist, it is updated
Copy the code
dic5
Copy the code
{' name ':' xiao Ming ', 'age: 25,' score ': [100, 99, 98],' address ':' 'shenzhen city, guangdong province,' birth ':' 1993-08-08 ', 'sex' : 'male'}Copy the code

Dictionary method 4: pop()

Used to obtain the value of the specified key and delete the entire key-value pair.

dic5
Copy the code
{' name ':' xiao Ming ', 'age: 25,' score ': [100, 99, 98],' address ':' 'shenzhen city, guangdong province,' birth ':' 1993-08-08 ', 'sex' : 'male'}Copy the code
dic5.pop("sex")
Copy the code
'male'Copy the code

Looking at the following dictionary, we find that the sex key pair has been deleted:

dic5
Copy the code
{' name ':' xiao Ming ', 'age: 25,' score ': [100, 99, 98],' address ':' 'shenzhen city, guangdong province,' birth ':' 1993-08-08 '}Copy the code

Dictionary method 5: popItem ()

This method is used to randomly pop up a key-value pair in a dictionary. It’s not random.

The Pop method of a Python list always pops the last element. The dictionary’s popItem () method also pops up the last key-value pair

dic5
Copy the code
{' name ':' xiao Ming ', 'age: 25,' score ': [100, 99, 98],' address ':' 'shenzhen city, guangdong province,' birth ':' 1993-08-08 '}Copy the code
dic5.popitem()  # Last one
Copy the code
('birth', '1993-08-08')
Copy the code
dic4
Copy the code
{' name ':' xiao Ming ', 'age: 25, 89, 111,' sex ':' male ', 'score' : [100, 98, 99]}Copy the code
k,v = dic4.popitem()  # Assign values to both variables via sequential unpacking

print(k)
print(v)
Copy the code
score
[100, 98, 99]
Copy the code

Dictionary method 6: setDefault ()

The setdefault() method is also used to get the value of the corresponding value based on the key.

  • If the key to be obtained does not exist in the dictionary, you can set a default value for the key and return the value corresponding to the key.
  • If the key exists in the dictionary, return the value of the key
dic5
Copy the code
{' name ':' xiao Ming ', 'age: 25,' score ': [100, 99, 98],' address ':' the guangdong province shenzhen '}Copy the code
dic5.setdefault("sex"."Male")   No sex key exists in # dic5
Copy the code
'male'Copy the code
dic5.setdefault("name"."Little red") If the # name key exists, the value in the dictionary is returned
Copy the code
'Ming'Copy the code

Fromkeys ()

This method creates a dictionary with a given number of keys. The default value for each key is None. You can also pass in an additional parameter as the default value

dic8 = dict.fromkeys(["Little red"."Xiao Ming"])  # list form
dic8
Copy the code
{' xiao Hong ': None, 'Xiao Ming ': None}Copy the code

The default value for all methods is None

dict.fromkeys(("Little red"."Xiao Ming"))   # tuple form
Copy the code
{' xiao Hong ': None, 'Xiao Ming ': None}Copy the code

You can also pass in a default value:

dict.fromkeys(["Xiao Ming"."Chou"].22)
Copy the code
{' Xiao Ming ': 22, 'Xiao Zhou ': 22}Copy the code

Dictionary 3 magic weapons

Key 1: Keys ()

All keys used to view the dictionary

dic5
Copy the code
{' name ':' xiao Ming ', 'age: 25,' score ': [100, 99, 98],' address ':' 'shenzhen city, guangdong province,' sex ':' male '}Copy the code
dic5.keys()
Copy the code
dict_keys(['name', 'age', 'score', 'address', 'sex'])
Copy the code
for key in dic5.keys():  Loop through each key
    print(key)
Copy the code
name
age
score
address
sex
Copy the code

We can see from the following code that when we iterate over the dictionary, the default is to take the key of the dictionary:

for i in dic5:
    print(i)
Copy the code
name
age
score
address
sex
Copy the code

Values ()

Used to return all values in the dictionary

dic5.values()
Copy the code
The dict_values ([' xiaoming, 25, (100, 99, 98), shenzhen city, guangdong province, 'male'])Copy the code
list(dic5.values())
Copy the code
[' Xiao Ming ', 25, [100, 99, 98], 'Shenzhen ', Guangdong Province,' Male ']Copy the code

Dictionary magic 3: Items ()

Used to return all key-value pairs

dic5.items()
Copy the code
Dict_items ([(' name ', 'xiao Ming), (' age, 25), (' score' [100, 99, 98]), (' address ', 'shenzhen city, guangdong province), (' sex' and 'male')])Copy the code
for item in dic5.items():
    print(item)
Copy the code
(' name ', 'xiao Ming) (25)' age '(' score' [100, 99, 98]) (' address ', 'shenzhen city, guangdong province) (' sex' and 'male')Copy the code

Since we can print key-value pairs directly through items(), we can get the keys and values directly

for k,v in dic5.items():
    print(k,v)
Copy the code
Name Xiaoming age 25 score [100, 99, 98] Address Shenzhen, Guangdong Sex maleCopy the code