|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
str() ,int(), list(), tuple().... 这些都是工厂函数,分别对应一个类型
字典的内建方法:fromkeys(...) , keys() , values() , items()
fromkeys(...): dict.fromkeys(S[,v]) -> New dict with keys from S and values equal to v (v defaults to None)
>>> dict1 = {} # 创建一个空字典
>>> dict1.fromkeys((1,2,3)) # fromkeys() 只给一个参数,那么默认第二个参数就是None
{1: None, 2: None, 3: None}
>>> dict1.fromkeys((1,2,3),'Number') # 这里给第二个参数,就会给到前面的每一个键当作其值
{1: 'Number', 2: 'Number', 3: 'Number'}
>>> dict1.fromkeys((1,2,3),('one','two','three')) # 这里会把'one','two','three'当一个整体, 当一个参数
{1: ('one', 'two', 'three'), 2: ('one', 'two', 'three'), 3: ('one', 'two', 'three')}
>>> dict1.fromkeys((1,3),'数字') # 这里重新创建一个新字典
{1: '数字', 3: '数字'}
keys(): 返回字典键的引用,values():返回字典值的引用,items() 返回字典项的引用 dir(dict) 查看字典内建方法
>>> dict1 = dict1.fromkeys(range(8),'赞')
>>> dict1
{0: '赞', 1: '赞', 2: '赞', 3: '赞', 4: '赞', 5: '赞', 6: '赞', 7: '赞'}
>>> for eachKey in dict1.keys(): # 返回字典键
print(eachKey)
0
1
2
3
4
5
6
7
>>> for eachValue in dict1.values(): # 返回字典值
print(eachValue)
赞
赞
赞
赞
赞
赞
赞
赞
>>> for eachItem in dict1.items(): # 返回字典项
print(eachItem)
(0, '赞')
(1, '赞')
(2, '赞')
(3, '赞')
(4, '赞')
(5, '赞')
(6, '赞')
(7, '赞')
>>> print(dict1[7])
赞
>>> print(dict1[8]) # 打印字典中不存在的键会报错
Traceback (most recent call last):
File "<pyshell#65>", line 1, in <module>
print(dict1[8])
KeyError: 8
>>> dict1.get(8)
>>> print(dict1.get(8)) # 用get打印字典中不存在的键,会返回None
None
>>> dict1.get(8,'木有!') # get(),两个参数,如果没有第1个参数,就返回第二个参数
'木有!'
>>> dict1.get(7,'木有') # get(),两个参数,如果第1个参数存在,就返回第1个参数对应的值
'赞'
>>> a
{3: 'three', 4: 'four'}
>>> a.setdefault('小白') # setdefault(),访问不存在的键会默认给None值
>>> a
{'小白': None, 3: 'three', 4: 'four'}
>>> a.setdefault(5,'five') # 新增一项
'five'
>>> a
{'小白': None, 3: 'three', 4: 'four', 5: 'five'}
>>> b = {'小白':'狗'}
>>> a.update(b) # 更新a
>>> a
{'小白': '狗', 3: 'three', 4: 'four', 5: 'five'}
>>> 7 in dict1 # 成员操作符in ,用来判断键是否在字典中
True
>>> 8 in dict1
False
>>> dict1
{0: '赞', 1: '赞', 2: '赞', 3: '赞', 4: '赞', 5: '赞', 6: '赞', 7: '赞'}
>>> dict1.clear() # 清空字典
>>> dict1
{}
清空字典跟直接 dict1 = {} , 两个有区别。看下例
>>> dict1 = {}
>>> a = {'姓名':'小甲鱼'}
>>> b = a
>>> b
{'姓名': '小甲鱼'}
>>> a = {}
>>> a
{}
>>> b
{'姓名': '小甲鱼'}
>>> a = b
>>> a
{'姓名': '小甲鱼'}
>>> b
{'姓名': '小甲鱼'}
>>> a.clear()
>>> a
{}
>>> b
{}
>>> a = {1:'one',2:'two',3:'three'}
>>> b = a.copy() # a复制一份给b
>>> c = a # 给a变量的内容再加一个标签c
>>> c
{1: 'one', 2: 'two', 3: 'three'}
>>> a
{1: 'one', 2: 'two', 3: 'three'}
>>> b
{1: 'one', 2: 'two', 3: 'three'}
>>> id(a) # a和c id一致,跟copy的b不一致
192299304
>>> id(b)
192293544
>>> id(c)
192299304
>>> c[4] = 'four' # 给c 字典添加一项
>>> c
{1: 'one', 2: 'two', 3: 'three', 4: 'four'}
>>> a
{1: 'one', 2: 'two', 3: 'three', 4: 'four'}
>>> b # b 字典不会变
{1: 'one', 2: 'two', 3: 'three'}
>>> a.pop(2) # 删除键为2的值
'two'
>>> a
{1: 'one', 3: 'three', 4: 'four'}
>>> a.popitem() # popitem() 随机删除一项,字典没有顺序
(1, 'one')
>>> a
{3: 'three', 4: 'four'}
|
|