【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 @ 2023-03-20 19:53  植树chen  阅读(122)  评论(0)    收藏  举报