'''使用{}创建字典'''
scores = {'章三':100,'里斯':98,'王武':45}
print(scores)
print(type(scores))
'''第二种创建方式'''
stuednt = dict(name = 'jack', age = 20)
print(stuednt)
'''空字典'''
d = {}
'''查询 获取字典元素'''
print(scores['章三']) #不存在会报错
# 第二种 不存在不会报错 返回none
print(scores.get('章三'))
print(scores.get('章三1'))
print(scores.get('章三1',999)) #999不存在返回默认值
print(scores.get('章三1',"不能存在")) #999不存在返回默认值
'''key的判断'''
print('章三' in scores)
print('章三' not in scores)
del scores['章三']
# scores.clear() #清空
print(scores)
scores['陈留'] = 98
print(scores)
scores['陈留'] = 100
print(scores)
''' 视图操作 '''
# 获取key
keys = scores.keys()
print(keys)
print(type(keys))
# 获取value
values = scores.values()
print(values)
print(type(values))
# 获取item
keysvalues = scores.items()
print(keysvalues)
print(type(keysvalues))
# 遍历
for item in scores:
print(item,scores[item],scores.get(item))
# value 不能重复 value可以
scores1 = {'订单':12313,"订单":12333123123}
print(scores1)
# 无序
# key必须是不可变对象
#字典可以根据需要动态伸缩
#字典浪费较大内存,空间换时间数据结构
'''字典生成式'''
items=['Fruits','Books','others']
prices = [96,87,345]
d = { item.upper():price for item,price in zip(items,prices)}
print(d)
python 字典
最新推荐文章于 2024-10-02 10:53:34 发布