python-Dict(字典)[未完待续]

简介

字典是另一种可变容器模型,且可存储任意类型对象。

字典创建

key只能为不变类型,如数字、字符串、元组

>>> a = dict(one=1, two=2, three=3)
>>> b = {'one': 1, 'two': 2, 'three': 3}
>>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
>>> d = dict([('two', 2), ('one', 1), ('three', 3)])
>>> e = dict({'three': 3, 'one': 1, 'two': 2})
>>> a == b == c == d == e
True

方法:

  • len(d): 返回字典的长度。
  • d[key]: 通过key,返回d的值。
    当key找不到的情况:
    查看__missing__(key)是否已经被定义?
    如果没有被定义:那个抛出异常
    如果定义了:按missing里面处理
>>> class Counter(dict):
...     def __missing__(self, key):
...         return 0
>>> c = Counter()
>>> c['red']
0
>>> c['red'] += 1
>>> c['red']
1

d[key] = value:设置值。

del d[key]:删除一条词条。

key in d:返回key值是否存在字典中。

key not in d:返回key值是否不在字典中。

iter(d):返回一个字典的key值可迭代。这是一个快捷方式对于,iter(d.keys()).

clear():删除词典中的词条。

copy():返回一个词典的复制。——>注意:这是一个浅拷贝。

classmethod fromkeys(iterable[, value]) 类方法:
创建一个新字典,使用可迭代的键和设置为value的值。

fromkeys() 是一个类方法返回一个新字典,值默认设置为None

get(key[, default]):或者对应key的值,不然返回default的内容,如果default没有设置那么返回None。

items():返回字典项((键,值)对的新视图

keys():返回一个字典的keys的值的视图。

pop(key[, default]):如果key的值在字典中,删除它,然后返回它的value值。不然返回default,如果default没有给出,那么抛出异常。

popitem():后进先出的删除并返回一个键值对。
如果字典空,那么抛出KeyError异常。

setdefault(key[, default])
如果key存在,那么返回它的值。如果没有,插入一个defualt值到key中。default默认为None

update([other]):更新字典的键值对,返回None.

update() accepts either another dictionary object or an iterable of key/value pairs (as tuples or other iterables of length two). If keyword arguments are specified, the dictionary is then updated with those key/value pairs: d.update(red=1, blue=2).

values():返回一个新的字典的value的视图对象。

未完待续…

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值