14_Python advanced variable types of dictionaries (Dict)

It is also a list of dictionary type data structure, but its elements use the "key - the value" approach to storage.

Dictionary definition

# 字典是一个无序的数据集合,使用print函数输出字典时,通常输出的顺序和定义的顺序是不一致的!
xiaoming = {"name": "小明",
            "age": 18,
            "gender": True,
            "height": 1.75,
            "weight": 75.5}
print(xiaoming)

Here Insert Picture Description

Basic use dictionary

xiaoming_dict = {"name": "小明"}

# 1. 取值
print(xiaoming_dict["name"])
# 在取值的时候,如果指定的key不存在,程序会报错!
# print(xiaoming_dict["name123"])

# 2. 增加/修改
# 如果key不存在,会新增键值对
xiaoming_dict["age"] = 18
# 如果key存在,会修改已经存在的键值对
xiaoming_dict["name"] = "小小明"

# 3. 删除
xiaoming_dict.pop("name")
# 在删除指定键值对的时候,如果指定的key不存在,程序会报错!
# xiaoming_dict.pop("name123")

print(xiaoming_dict)

Other use dictionary

xiaoming_dict = {"name": "小明",
                 "age": 18}

# 1. 统计键值对数量
print(len(xiaoming_dict))

# 2. 合并字典
temp_dict = {"height": 1.75,
             "age": 20}

# 注意:如果被合并的字典中包含已经存在的键值对,会覆盖原有的键值对
xiaoming_dict.update(temp_dict)

# 3. 清空字典
xiaoming_dict.clear()

print(xiaoming_dict)

Dictionary traversal

xiaoming_dict = {"name": "小明",
                 "qq": "123456",
                 "phone": "10086"}

# 迭代遍历字典
# 变量k是每一次循环中,获取到的键值对的key
for k in xiaoming_dict:

    print("%s - %s" % (k, xiaoming_dict[k]))

Dictionary application

# 使用 多个键值对,存储 描述一个 物体 的相关信息 —— 描述更复杂的数据信息
# 将 多个字典 放在 一个列表 中,再进行遍历
card_list = [
    {"name": "张三",
     "qq": "12345",
     "phone": "110"},
    {"name": "李四",
     "qq": "54321",
     "phone": "10086"}
]

for card_info in card_list:
    print(card_info)

Here Insert Picture Description

Published 66 original articles · won praise 111 · views 320 000 +

Guess you like

Origin blog.csdn.net/shengshengshiwo/article/details/104065727