Python字典

复制代码
字典中的key是无序的
字典类型的创建方式:
(1)使用{}直接创建字典
d = {key1:value1,key2:value2}
(2)使用内置函数dict()创建字典
# 通过映射函数创建字典
zip(lst1,lst2)
dict(key1=value1,key2=value2)

# d.items()字典的方法,返回一个包含字典键值对的视图对象。每个键值对是一个元组 (key, value)。
字典元素的取值:d[key]或d.get(key)
字典元素的遍历:
(1)遍历出key与value的元组
for element in d.items():
    pass
(2)分别遍历出key和value
for key,value in d.items():
    pass
python 复制代码
print("-----------字典创建------------")
# (1)使用{}直接创建字典
d = {10:'cat',20:'dog',30:'pet',40:'zoo'}
print(d)

# zip函数
lst1 = [10,20,30,40]
lst2 = ['cat','dog','pet','zoo']
zip1 = zip(lst1,lst2)
print(zip1)
d = dict(zip1)
print(d)
d = dict(cat=10,dog=20)
print(d)
print(type(d))

# 使用参数创建字典
d = dict(cat=10,dog=20)
print(d)
print(type(d))

t = (10,20,30,40)
print({t:10})  # t是key,10是value,元组可以作为字典中的key

# 字典属于序列
print(max(d))
print(min(d))
print(len(d))

print("-----------字典访问与遍历------------")
d = {'hello':10,'world':20,'python':30}
# 访问
print(d['hello'])
print(d.get('hello'))
# 二者有区别,如果key不存在,d[key]报错,d.get(key)可以指定默认值
# print(d['java'])
print(d.get('java'))  # 输出为None
# 遍历
for item in d.items():
    print(item)  # key = value组成的一个元素
for key,value in d.items():
    print(key,value)
相关推荐
默_笙1 天前
🍙 给每个请求过安检:FastAPI 是怎么把校验写进类型注解的
python
小羊没烦恼!1 天前
初探性能优化——2个月到4小时的性能提升
java·开发语言·windows·算法·c#
qq_426003961 天前
启动playwright录制codegen生成自动化测试脚本
python·自动化
虎头金猫1 天前
4K 视频总卡在公网带宽?用 N1 + OpenList 把网盘播放链路重新理顺
运维·服务器·网络·python·容器·beautifulsoup·pandas
长沙三为智能科技1 天前
家政小程序开发从0到上线:五阶段交付流程与验收清单
python
伞伞悦读1 天前
【第38期】Python 模块与包详解:import、from、模块搜索路径、包结构和 __init__
开发语言·python
只睡四小时1 天前
Canvas 弹道联机实战:700 行 + 固定时间步长
python·websocket·html5·游戏开发·canvas
C语言小火车1 天前
C/C++ 为什么需要编译器?
开发语言·c++
奇思妙想聪明勤奋的小羊1 天前
DeepAgents第5章:子Agent 与上下文隔离—让 Agent学会委派
人工智能·python·学习·语言模型
lpfasd1231 天前
2026年第38周GitHub趋势周报
python·科技·github