python入门容器-字典dict Day05

字典 dict

定义

  1. 由一系列键值对组成的可变散列容器。
  2. 散列:对键进行哈希运算,确定在内存中的存储位置,每条数据存储无先后顺序。
  3. 键必须惟一且不可变(字符串/数字/元组),值没有限制。

基础操作

创建字典:

        字典名 = {键1:值1,键2:值2}

        字典名 = dict (可迭代对象)

添加/修改元素:

        语法:

            字典名[键] = 数据

        说明:

            键不存在,创建记录。

            键存在,修改值。

获取元素:

        变量 = 字典名[键]  # 没有键则错误

遍历字典:

       for 键名 in 字典名:

              字典名[键名]

       for 键名,值名 in 字典名.items():

扫描二维码关注公众号,回复: 14665705 查看本文章

               语句

删除元素:

        del 字典名[键]

"""
    字典dict基本操作:
        创建
        获取元素
        遍历
        新增
        修改
        删除
"""

# 列表擅长存储单一维度的信息
# 字典擅长存储多个维度的信息
# 1.创建
# 语法1:字典名 = {键1:值1,键2:值2}
# 创建字典存储香港信息、字典存储上海信息、字典存储新疆信息
dict_HongKong = {
    "region":"香港",
    "new":15,
    "now":393,
    "total":4801,
    "cure":4320,
    "death":88
}


dict_shanghai = {
    "region": "上海",
    "new": 6,
    "now": 61,
    "total": 903,
    "cure": 835,
    "death": 7
}

dict_xingjiang = {
    "region": "新疆",
    "new": 0,
    "now": 49,
    "total": 902,
    "cure": 850,
    "death": 3
}
# 语法2:字典名 = {键1:值1,键2:值2}
# 对于可迭代对象元素的格式要求:一分为二
list01 = ["悟空", ("猪", "八戒"), ["唐", "三藏"]]
dict02 = dict(list01)
print(dict02)

# 2.获取元素
# 在终端中打印香港的现有人数
print(dict_HongKong["now"])
# 在终端中打印上海的新增和现有人数
print(dict_shanghai["new"])
print(dict_shanghai["now"])
# 新疆新增人数增加1
dict_xingjiang["new"] += 1

# 3.删除
# 删除香港现有人数信息
del dict_HongKong["now"]
# 删除新疆新增人数信息
del dict_xingjiang["new"]
# 删除上海的新增和现有信息
del dict_shanghai["new"],dict_shanghai["now"]

# 4.遍历
for key,value in dict_xingjiang.items():
    print(key)
    print(value)

for key in dict_HongKong:
    print(key,end = " ")

for value in dict_shanghai.values():
    print(value)


for key,value in dict_shanghai.items():
    if value == 61:
        print(key)
        break


"""
    字典dict基本操作
        添加
        修改
"""
dict_gsx = {
    "name":"郭士信",
    "age":26,
    "sex":"女"
}
#添加
if "money" not in dict_gsx:
    dict_gsx["money"] = 1000000
# 修改
if "age" in dict_gsx:
    dict_gsx["age"] = 27
# 读取
print(dict_gsx["name"])


字典推导式

定义:

使用简易方法,将可迭代对象转换为字典。

语法:

{键:值 for 变量 in 可迭代对象}

{键:值 for 变量 in 可迭代对象 if 条件}

"""
字典推导式
    练习1:
    将两个列表,合并为一个字典
            姓名列表["张无忌","赵敏","周芷若"]
            房间列表[101,102,103]
    {101: '张无忌', 102: '赵敏', 103: '周芷若'}
    练习2:
    颠倒练习1字典键值
    {'张无忌': 101, '赵敏': 102, '周芷若': 103}
"""
list_name = ["张无忌","赵敏","周芷若"]
list_room = [101,102,103]
result = {list_name[i]:list_room[i] for i in range(len(list_name))}
print(result)

new_result = {value:key for key,value in result.items()}
print(new_result)

字典 -- > 列表

# 所有键值对的列表 [(键1,值1),(键2,值2)]
print(list(dict_gsx.items()))
# 所有Key的列表
print(list(dict_gsx))
# 所有value的列表
print(list(dict_gsx.values())) 

猜你喜欢

转载自blog.csdn.net/LOVE_Me__/article/details/122711255