Python之字典与集合

字典

字典使用名称—内容进行数据结构的构建,在Python中分别对应着键(key)—值(value),习惯上称为键值对,下面举个例子:

city_popularity={'上海':'first','北京':'second','杭州':'third'}

上面就是字典的写法,那么我们来一一试验字典的性质:

city_popularity={'上海':'first','北京':'second','杭州':'third'}
city_popularity['深圳']='fourth'
print(city_popularity)
# {'上海':'first','北京':'second','杭州':'third','深圳':'fourth'}

这是字典元素的添加

city_popularity={'上海':'first','北京':'second'}
city_popularity.update({'杭州':'third','深圳':'fourth'})
print(city_popularity)
# {'上海':'first','北京':'second','杭州':'third','深圳':'fourth'}

添加多个元素用update()方法

city_popularity={'上海':'first','北京':'second','杭州':'third'}
del city_popularity['杭州']
print(city_popularity)
# {'上海':'first','北京':'second'}

删除字典中元素可以用del方法

city_popularity={'上海':'first','北京':'second','杭州':'third'}
print(city_popularity['上海'])
# first

注意字典中只能用相应键来获得对应值,不能用索引

集合

集合中元素是无序的而且各不相同,所以不能用索引和切片
只可以添加和删除其中的元素,例如:

a={1,2,3,4}
a.add(5)
print(a)
# {1,2,3,4,5}
a.discard(5)
print(a)
# {1,2,3,4}

上面是添加和删除集合元素的例子

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值