Chapter 6: Python basic data structure - dictionary

A dictionary is the most basic data structure in Python.

Dictionaries are another mutable container model and can store objects of any type.

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

Dictionaries are used as Python keywords and built-in functions, and the variable name is not recommended to be named dict .

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

Values ​​can take any data type, but keys must be immutable, such as strings, numbers.

1. An overview of the dictionary

  • what is a dictionary

    • Dictionaries are one of the most basic data structures in Python , and like lists, they are mutable sequences
    • Store data in the form of key-value pairs, and a dictionary is an unordered sequence
  • Schematic diagram of a dictionary

image-20220819185856654

  • The implementation principle of the dictionary
    • The implementation principle of the dictionary is similar to that of looking up a dictionary. Looking up a dictionary is to first look up the corresponding page number according to the radical or pinyin. The dictionary in Python looks up the location of the Value according to the Key

Second, the creation of the dictionary

  • The most common way: use curly braces

    • code demo
    """1、使用{}创建字典"""
    scores = {
          
          "张三": 100, "李四": 98, "王五": 88}
    print(scores)
    print(type(scores))
    
  • Use the built-in function dict()

    • code demo
    """2、使用内置函数dict()创建"""
    student = dict(name="tom", age=19)
    print(student)
    
  • create an empty dictionary

    • code demo
    """创建一个空字典"""
    dict3 = {
          
          }
    print(dict3)
    

3. Common operations of dictionaries

3.1 Obtaining elements in the dictionary

  • method to get the element

    Method to get dictionary elements example the difference
    [] score["Zhang San"] [] If the specified key does not exist in the dictionary , a KeyError exception is thrown
    get() method score.get("Zhang San") The get() method takes a value. If the specified key does not exist in the dictionary , it will not throw KeyError but return None . You can set the default Value
    through parameters so that it returns when the specified key does not exist.
    • code demo
    """获取字典中的元素"""
    scores = {
          
          "张三": 100, "李四": 98, "王五": 88}
    """第一种方式,使用[]"""
    print(scores["张三"])
    
    """第二种方式,使用get()方法"""
    print(scores.get("张三"))
    
    """差异性"""
    # print(scores["阿萨德"])
    print(scores.get("阿萨德"))
    print(scores.get("阿达", 99))
    

3.2 Judgment of elements in the dictionary

  • The judgment of the key in the dictionary

    method/statement illustrate
    in Returns True if the specified Key exists in the dictionary
    not in Return True if the specified Key does not exist in the dictionary
    • code demo
    """key的判断"""
    scores = {
          
          "张三": 100, "李四": 98, "王五": 88}
    print("张三" in scores)
    print("张三" not in scores)
    
    print("阿达" in scores)
    print("阿达" not in scores)
    

3.3 Deletion, addition and modification of elements in the dictionary

  • code demo
"""删除指定的key——value"""
del scores["张三"]
print(scores)
# 清空字典所有元素
scores.clear()
print(scores)

"""字典元素的新增操作"""
scores["柯蓝"] = 100
print(scores)

"""字典元素的修改操作"""
scores["柯蓝"] = 10
print(scores)

3.4 Get a view of the dictionary

  • Three ways to get a dictionary view
method illustrate
key() Get all the keys in the dictionary
values() Get all the values ​​in the dictionary
items() Get all the keys in the dictionary: vaule key-value pairs
  • code demo
scores = {
    
    "张三": 100, "李四": 98, "王五": 88}
"""获取所有的key"""
keys = scores.keys()
print(keys)
print(type(keys))
# 将所有的key组成的视图转换成列表
print(list(keys))

print("\n")
"""获取所有的value"""
values = scores.values()
print(values)
print(type(values))
print(list(values))

print("\n")
"""获取所有的key-value"""
items = scores.items()
print(items)
print(type(items))
print(list(items))  # 转换之后的列表元素有元组组成

3.5 Traversal of dictionary elements

  • code demo
scores = {"张三": 100, "李四": 98, "王五": 88}
"""字典元素的遍历"""
for item in scores:
    print(item)
    print(item, scores[item], scores.get(item))

Fourth, the characteristics of the dictionary

  • All elements in the dictionary are key-value key-value pairs. The key is not allowed to be repeated, but the value is allowed to be repeated
  • The elements in the dictionary are unordered
  • The keys in the dictionary must be immutable objects
  • Dictionaries can also be dynamically scaled as needed
  • Dictionary will waste a lot of memory, it is a data structure that uses space for time

Five, the generation of the dictionary

Dictionary generating formula, referred to as "the formula for generating a dictionary"

  • Call the built-in function - zip()

    • Used to take an iterable object as a parameter, pack the elements in the object into a tuple, and then return a list of these tuples
  • code demo

"""已知两个列表,生成一个字典
items = ['Fruits', 'Books', 'Others']
prices = [96, 78, 85,100,200]
"""
items = ['Fruits', 'Books', 'Others']
prices = [96, 78, 85,100,45566]

d = {
    
    item.upper(): price for item, price in zip(items, prices)}
print(d)
# 如果用于生成的两个列表中的参数个数不相等,取较小的一个

Guess you like

Origin blog.csdn.net/polaris3012/article/details/130504945