Python数据结构----字典


字典

概念

Python内置数据结构之一,与列表一样是一个可变序列
以键值对的方式存储数据,字典是一个无序的序列
相当于unordered_map,底层是哈希存储

字典的创建

在这里插入图片描述

#使用{}创建字典
scores={'wangchen':1,'hedenghui':2,'hezhaoxuan':3}
print(scores)

#使用dict()创建
student=dict(name='jack',age=19)
print(student)

#空字典
d={}
print(d)

在这里插入图片描述

字典的获取

两种方式,[]或者get(),下面说明了两种区别
在这里插入图片描述

scores={'wangchen':1,'hedenghui':2,'hezhaoxuan':3}
print(scores['wangchen'])
#print(scores['wang']) 报异常错误
print(scores.get('wangchen'))
print(scores.get('wang'))#不存在返回None
print(scores.get('马琦',100))#不存在返回指定值100

在这里插入图片描述

字典增删改

#增删改
scores={'wangchen':1,'hedenghui':2,'hezhaoxuan':3}
print(scores)
scores['chenliu']=99
print(scores)
scores['chenliu']=100
print(scores)
del scores['wangchen']
print(scores)
scores.clear()
print(scores)

在这里插入图片描述

获取字典视图

在这里插入图片描述

scores={'wangchen':1,'hedenghui':2,'hezhaoxuan':3}
print(scores.keys())
print(type(scores.keys()))

print(scores.values())
print(type(scores.values()))

print(scores.items())
print(type(scores.items()))

在这里插入图片描述

字典的遍历

scores={'wangchen':1,'hedenghui':2,'hezhaoxuan':3}
for item in scores:
    print(item,scores[item])

字典的特点

  1. 字典中的所有元素都是一个key-value对,key不允许重复,value可以重复
  2. 字典中的元素是无序的
  3. 字典中的key必须是不可变对象
  4. 字典中也可以根据需要动态地伸缩
  5. 字典会浪费较大的内存,是一种使用空间换时间的数据结构

字典生成式

items=['first','second','third']
nums=[1,2,3]

d={item:num for item,num in zip(items,nums)}
print(d)
d={item.upper():num for item,num in zip(items,nums)}
print(d)

在这里插入图片描述

  • 0
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值