【Python】数据结构:字典,元素为键值对表示

1.字典

可以存储任意类型对象,每个元素由键值对组成。花括号

scores = {'张三': 99, '李四': 64, '王五': 88}
print(scores) # {'张三': 99, '李四': 64, '王五': 88}
print(scores['李四']) # 64
for key in scores: #遍历
print(f'{key}:{scores[key]}') # 张三:99...
scores['李四'] = 84
scores['老刘'] = 99
scores.update(钱七=67, 八万=88) #更新元素
print(scores) # {'张三': 99, '李四': 84, '王五': 88, '老刘': 99, '钱七': 67, '八万': 88}
if '老十' in scores:
print(scores['老十'])
print(scores.get('老十')) # None
print(scores.get('老十', 60)) # 60,通过键获取值,设置默认值60
print(scores.popitem()) # ('八万', 88) #删除字典中的元素
print(scores.popitem()) # ('钱七', 67)
print(scores.pop('张三', 100)) # 99
scores.clear() #清空字典
print(scores) # {}

2.创建字典

# 构造器语法
item1 = dict(one=1, two=2, three=3, four=4)
print(item1) # {'one': 1, 'two': 2, 'three': 3, 'four': 4}
# 使用zip函数将两个序列压成字典
item2 = dict(zip(['a', 'b', 'c'], '123'))
print(item2) # {'a': '1', 'b': '2', 'c': '3'}
# 推导式语法
item3 = {num: num ** 2 for num in range(1, 10)}
print(item3) # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
posted @   植树chen  阅读(111)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
点击右上角即可分享
微信分享提示