<Python's Dictionary>——《Python》

Table of contents

1. Dictionary

1.1 What is a dictionary

1.2 Create a dictionary

1.3 Find the key

1.4 Add/modify elements

1.5 Delete elements

1.6 Traversing dictionary elements

1.7 Take out all keys and values

1.8 Legal key types


1. Dictionary

1.1 What is a dictionary

A dictionary is a structure that stores key-value pairs.
Key-value pair is a very widely used concept in computer/life.
Make a one-to-one mapping between the key (key) and the value (value), and then you can quickly find the value according to the key.
For example, every student in the school will have a unique student number.
Once you know the student number, you can identify the student.
Here the "student number" is the "key", and the "classmate" is the "value".

1.2 Create a dictionary

(1) Create an empty dictionary. Use { } to represent a dictionary
#1.创建字典

a = {}
print(type(a))
b = dict()
print(type(b))
(2) Specify the initial value while creating
(3) Use ', ' between key-value pairs, and use: between key and value. (It is recommended to add a space after the colon).
(4) Use print to print the contents of the dictionary
student = { 'id': 1, 'name': 'zhangsan' }
print(student)

The above dictionary student contains two key-value pairs:

1) 'id': 1 key is 'id', value is 1

2) 'name': 'zhangsan' key is 'name', value is 'zhangsan'

Note:

  • The types of keys in a dictionary are not necessarily the same
  • The value types in a dictionary are not necessarily all the same
  • Dictionaries have constraints on the type of key
  • Dictionaries have no constraints on the type of value

(5) In order to make the code more standardized and beautiful, multiple key-value pairs are often written in multiple lines when creating a dictionary.

student = {
    'id': 1,
    'name': 'zhangsan'
}
(6) The last key-value pair can be written later or not.
student = {
    'id': 1,
    'name': 'zhangsan',
}

 

1.3 Find the key

  • Use in to determine whether the key exists in the dictionary. Returns a boolean value
student = {
    'id': 1,
    'name': 'zhangsan',
}
print('id' in student)
print('score' in student)
  • Use [ ] to get the value of the element in a way similar to removing the subscript. It's just that the "subscript" here is the key. (It may be an integer, or it may be other types such as a string).

#2.使用 [ ]来判定key获取到value
student = {
    'id': 1,
    'name': 'zhangsan',
    99:'forever'
}
print(student['id'])
print(student['name'])
print(student[99])
print(student['score'])

If the key does not exist in the dictionary, an exception will be thrown.
student = {
    'id': 1,
    'name': 'zhangsan',
}
print(student['score'])

Note:

  • For dictionaries, using in or [] to get value is a very efficient operation!
  • For lists, using in is relatively inefficient (you need to traverse the entire list), while using [ ] is more efficient (similar to subscripting arrays/order tables)! 

1.4 Add/modify elements

Use [ ] to add/modify value according to key.
  • If the key does not exist, assign a value to the subscript operation, which is a new key-value pair
student = {
    'id': 1,
    'name': 'zhangsan',
}
student['score'] = 90
print(student)
#1.在字典中新增元素,使用[ ]来进行
student = {
    'id': 1,
    'name': 'zhangsan',
}
print(student)
#向字典里插入新的键值对
student['score'] = 90
print(student)
  • If the key already exists, assign a value to the subscript operation, which is to modify the value of the key-value pair.
#2.在字典中,根据key修改value,也是使用[ ]
student = {
    'id': 1,
    'name': 'zhangsan',
}
print(student)
#向字典里插入新的键值对
student['score'] = 90
print(student)
student['score'] = 99
print(student)

1.5 Delete elements

Use the pop method to delete the corresponding key-value pair according to the key.

#3.使用pop方法,根据key修改键值对
student = {
    'id': 1,
    'name': 'zhangsan',
    'score': 99
}
print(student)
student.pop('id')
print(student)

 1.6  Traversing dictionary elements

Traversal refers to the ability to take out an iterable object, the elements it contains, and perform some operations. The whole process requires no repetition.

The original intention of the dictionary is not for traversal, but for adding, deleting, modifying and checking.

The dictionary is a hash table, and the operation efficiency of adding, deleting, modifying and checking is very high! But the traversal of the dictionary is less efficient!

  • Directly use the for loop to get all the keys in the dictionary, and then you can take out each value.
student = {
    'id': 1,
    'name': 'zhangsan',
    'score': 80
}
for key in student:
    print(key, student[key])
Note:
In C++/Java, the storage order of the key-value pairs of the hash table is out of order!
But the hash table in Python has done special processing, similar to the queue to ensure first-in-first-out, the order of its traversal and printing is the order of insertion! So, Python's dictionary is not a simple "hash table"!   

1.7 Take out all keys and values

  • Use the keys method to get all the keys in the dictionary
student = {
    'id': 1,
    'name': 'zhangsan',
    'score': 80
}
print(student.keys())
Here dict_keys is a special type, which is specially used to represent all the keys of the dictionary. Most of the operations supported by tuples are also applicable to dict_keys.
  • Use the values ​​method to get all the values ​​in the dictionary
student = {
    'id': 1,
    'name': 'zhangsan',
    'score': 80
}
print(student.values())
Here dict_values ​​is also a special type, similar to dict_keys.
  • Use the items method to get all the key-value pairs in the dictionary.
student = {
    'id': 1,
    'name': 'zhangsan',
    'score': 80
}
print(student.items())
Here dict_items is also a special type, similar to dict_keys.

The traversal of the dictionary is realized with the help of the items() method:

student = {
    'id': 1,
    'name': 'zhangsan',
    'score': 99
}
for key, value in student.items():
    print(key, value)

 

1.8 Legal key types

Not all types can be used as dictionary keys.
A dictionary is essentially a hash table , and the key of the hash table is required to be "hashable", that is, a hash value can be calculated.
  • The hash value of an object can be calculated using the hash function.
  • Any type that can calculate the hash value can be used as the key of the dictionary.
print(hash(0))
print(hash(3.14))
print(hash('hello'))
print(hash(True))
print(hash(()))           # ( ) 是一个空的元组
  • A list cannot be hashed.
print(hash([1, 2, 3]))

 

  • Dictionaries can't calculate hashes either
print(hash({ 'id': 1 }))
Note:
  • Immutable objects are generally hashable!
  • Mutable objects are generally not hashable!
summary
  • Dictionaries are also a commonly used structure. All operations on dictionaries revolve around keys.
  • When you need to represent the scene of "key-value pair mapping", you can consider using a dictionary.
  • Dictionaries, lists, and tuples are commonly used built-in types in Python. Compared with int, str, and float, they can contain other elements inside! This class is called a container/collection class!

 

Guess you like

Origin blog.csdn.net/m0_57859086/article/details/128746812