Python introductory tutorial | Python3 dictionary (dict)

Python3 dictionary

Dictionary is another mutable container model and can store any type of object.
The dictionary in Python3 is an unordered, variable, iterable data structure, which consists of keys and corresponding values. Dictionaries are treated as mutable objects in Python, which means we can change, add or remove elements in the dictionary at any time.

The following are some basic features about Python3 dictionaries:

  • Key and value: Each element in the dictionary consists of a key and a value. Keys are unique and each key can only correspond to one value. Keys and values ​​are separated by colons, and key-value pairs are separated by commas.
  • Unordered: Dictionaries are unordered, which means that when you create a dictionary, the order of the elements may change over time. In Python 3.7 and later, dictionaries are sorted in insertion order, but this is not a guarantee.
  • Mutability: Python dictionaries are mutable, which means you can add, remove, or change elements in an existing dictionary.
  • Traversal: You can loop through all keys and values ​​in the dictionary.
  • Built-in functions and methods: Python dictionaries have many built-in functions and methods, such as get(), keys(), values(), items(), etc., which can help you better operate and use the dictionary.

Each key=>value pair of the dictionary is separated by a colon: and each pair is separated by a comma (,). The entire dictionary is included in curly braces {}. The format is as follows:

d = {
    
    key1 : value1, key2 : value2, key3 : value3 }

Note: dict asPython keywords and built-in functions, it is not recommended to name variables as dict.

Insert image description here

  • Keys must be unique, but values ​​do not.

  • The value can be of any data type, but the key must be immutable, such as strings and numbers.

A simple dictionary example:

tinydict = {
    
    'name': 'tarzan', 'likes': 666, 'url': 'www.tarzan.com'}

You can also create a dictionary like this:

tinydict1 = {
    
     'abc': 456 }
tinydict2 = {
    
     'abc': 123, 98.6: 37 }

Create empty dictionary

Use curly braces { } to create an empty dictionary:

Example:

# 使用大括号 {} 来创建空字典
emptyDict = {
    
    }
 
# 打印字典
print(emptyDict)
 
# 查看字典的数量
print("Length:", len(emptyDict))
 
# 查看类型
print(type(emptyDict))

The output of the above example is:

{}
Length: 0
<class ‘dict’>

Create a dictionary using the built-in function dict():

Example

emptyDict = dict()
# 打印字典
print(emptyDict)
# 查看字典的数量
print("Length:",len(emptyDict))
# 查看类型
print(type(emptyDict))

The output of the above example is:

{}
Length: 0
<class ‘dict’>

Access values ​​in a dictionary

Put the corresponding keys in square brackets, as in the following example:

#!/usr/bin/python3
 
tinydict = {
    
    'Name': 'Tarzan', 'Age': 7, 'Class': 'First'}
 
print ("tinydict['Name']: ", tinydict['Name'])
print ("tinydict['Age']: ", tinydict['Age'])

Example
The output result of the above example:

tinydict[‘Name’]: Tarzan
tinydict[‘Age’]: 7

If you access data using keys that are not in the dictionary, the following error will be output:

#!/usr/bin/python3
 
tinydict = {
    
    'Name': 'Tarzan', 'Age': 7, 'Class': 'First'}
 
print ("tinydict['Alice']: ", tinydict['Alice'])

The output of the above example is:

Traceback (most recent call last):
  File "test.py", line 5, in <module>
    print ("tinydict['Alice']: ", tinydict['Alice'])
KeyError: 'Alice'

Modify dictionary

The method of adding new content to the dictionary is to add new key/value pairs, modify or delete existing key/value pairs, as shown in the following example:

#!/usr/bin/python3
 
tinydict = {
    
    'Name': 'Tarzan', 'Age': 7, 'Class': 'First'}
 
tinydict['Age'] = 8               # 更新 Age
tinydict['School'] = "泰山教程"  # 添加信息

print ("tinydict['Age']: ", tinydict['Age'])
print ("tinydict['School']: ", tinydict['School'])

The output of the above example is:

tinydict['Age']:  8
tinydict['School']:  菜鸟教程

Delete dictionary element

You can delete a single element or clear the dictionary. Clearing only requires one operation.

To explicitly delete a dictionary, use the del command, as shown in the following example:

#!/usr/bin/python3
 
tinydict = {
    
    'Name': 'Tarzan', 'Age': 7, 'Class': 'First'}
 
del tinydict['Name'] # 删除键 'Name'
tinydict.clear()     # 清空字典
del tinydict         # 删除字典
 
print ("tinydict['Age']: ", tinydict['Age'])
print ("tinydict['School']: ", tinydict['School'])

But this throws an exception because the dictionary no longer exists after the del operation:

Traceback (most recent call last):
  File "/runoob-test/test.py", line 9, in <module>
    print ("tinydict['Age']: ", tinydict['Age'])
NameError: name 'tinydict' is not defined

Note: The del() method will also be discussed later.

Properties of dictionary keys

Dictionary values ​​can be any Python object, either standard or user-defined, but keys cannot.

Two important points to remember:

  • The same key is not allowed to appear twice. If the same key is assigned twice during creation, the latter value will be remembered, as in the following example:
#!/usr/bin/python3
 
tinydict = {
    
    'Name': 'Tarzan', 'Age': 7, 'Name': '小菜鸟'}
 
print ("tinydict['Name']: ", tinydict['Name'])

The output of the above example is:

tinydict[‘Name’]: tinydict

  • Keys must be immutable, so they can be used as numbers, strings or tuples, but not lists, as shown in the following example:
#!/usr/bin/python3

tinydict = {
    
    ['Name']: 'Tarzan', 'Age': 7}
 
print ("tinydict['Name']: ", tinydict['Name'])

The output of the above example is:

Traceback (most recent call last):
  File "test.py", line 3, in <module>
    tinydict = {
    
    ['Name']: 'Runoob', 'Age': 7}
TypeError: unhashable type: 'list'

Dictionary built-in functions & methods

The Python dictionary contains the following built-in functions:

function describe Example
len(dict) Count the number of dictionary elements, that is, the total number of keys >>> tinydict = {‘Name’: ‘Runoob’, ‘Age’: 7, ‘Class’: ‘First’}
>>> len(tinydict)
str(dict) Outputs a dictionary of printable string representations. >>> tinydict = {‘Name’: ‘Runoob’, ‘Age’: 7, ‘Class’: ‘First’}
>>> str(tinydict)
“{‘Name’: ‘Runoob’, ‘Class’: ‘First’, ‘Age’: 7}”
type(variable) Returns the input variable type, or dictionary type if the variable is a dictionary. >>> tinydict = {‘Name’: ‘Runoob’, ‘Age’: 7, ‘Class’: ‘First’}
>>> type(tinydict)
<class ‘dict’>
dict.clear() Delete all elements in the dictionary
dict.copy() Returns a shallow copy of the dictionary
dict.fromkeys() Create a new dictionary, using the elements in the sequence seq as the keys of the dictionary, and val is the initial value corresponding to all keys in the dictionary.
dict.get(key, default=None) Returns the value of the specified key. If the key is not in the dictionary, returns the default value set by default
key in dict Returns true if the key is in the dictionary dict, false otherwise
dict.items() Returns a view object as a list
dict.keys() Returns a view object
dict.setdefault(key, default=None) Similar to get(), but if the key does not exist in the dictionary, the key will be added and the value will be set to default
dict.update(dict2) Update the key/value pairs of dictionary dict2 into dict
dict.values() Returns a view object
pop(key[,default]) Delete the value corresponding to the dictionary key (key) and return the deleted value.
drink() Returns and deletes the last key and value pair in the dictionary.

Guess you like

Origin blog.csdn.net/weixin_40986713/article/details/134576844