字典的处理方法
clear
>>> d = {'name': 'Alice', 'age': 12}
>>> returend = d.clear()
>>> d
{}
>>> print(returend)
None
copy
- 返回一个新字典,其包含键-值对与原来的字典相同(浅复制:因为值本身是原件,而非副本)
>>> x = {'username': 'admin', 'machines': ['bar', 'foo', 'baz']}
>>> y = x.copy()
>>> y['username'] = 'mlh'
>>> y['machines'].remove('bar')
>>> y
{'username': 'mlh', 'machines': ['foo', 'baz']}
>>> x
{'username': 'admin', 'machines': ['foo', 'baz']}
- 当替换副本中的值时,原件不会受影响,但是修改副本中的值时,原件就会发生变化
-
深复制 :同时复制值及包含的所有值
>>> from copy import deepcopy
>>> d = {'names': ['Alfred', 'Bertrand']}
>>> c = d.copy()
>>> dc = deepcopy(d)
>>> d['names'].append('Clive')
>>> c
{'names': ['Alfred', 'Bertrand', 'Clive']}
>>> dc
{'names': ['Alfred', 'Bertrand']}
fromkeys
- 创建一个新字典,其中包含指定的键,每个键默认指定的为None
>>> dict.fromkeys(['name', 'age'])
{'name': None, 'age': None}
get
- 访问字典项时提供宽松的环境
- 如果访问字典中没有的项时会引发报错
>>> d = {}
>>> print(d.get('name'))
None
items
- 返还一个包含所有字典项的列表,其中每个元素都为(key——value)的形式,字典项在列表的顺序不确定
>>> d = {'title': 'Python web Site', 'url': 'http://www.python.org', 'spam': 0}
>>> d.items()
dict_items([('title', 'Python web Site'), ('url', 'http://www.python.org'), ('spam', 0)])
- 返回值属于一种字典视图的特殊类型,可以确定程度或者成员资格审查
>>> it = d.items()
>>> len(it)
3
>>> ('spam', 0) in it
True
>>> list(d.items())
[('title', 'Python web Site'), ('url', 'http://www.python.org'), ('spam', 0)]
pop
- 用于获取指定键相关联的值,并将键—值对从字典中删除
>>> d = {'x': 1, 'y': 2}
>>> d.pop('x')
1
>>> d
{'y': 2}
popitem
- 类似于list.pop,但是list.pop是弹出列表中的最后一个元素,而popitem随机的弹出一个字典项
>>> d = {'title': 'Python web Site', 'url': 'http://www.python.org', 'spam': 0}
>>> d.popitem()
('spam', 0)
>>> d
{'title': 'Python web Site', 'url': 'http://www.python.org'}
setdefault
- 与get类似,也能获取指定键相关联的值,但是setdefault在字典不包含指定键时,在字典中添加指定的键—值对
>>> d = {}
>>> d.setdefault('name', 'N/A')
'N/A'
>>> d
{'name': 'N/A'}
>>> d['name'] = 'Alice'
>>> d
{'name': 'Alice'}
>>> d.setdefault('name', 'N/A')
'Alice'
>>> d
{'name': 'Alice'}
update
>>> d = {'title': 'Python web Site', 'url': 'http://www.python.org', 'spam': 0}
>>> x = {'title': 'Python Language Website'}
>>> d.update(x)
>>> d
{'title': 'Python Language Website', 'url': 'http://www.python.org', 'spam': 0}
keys ,values
- keys: 返回一个由字典的键组成的字典视图
- values: 返回与一个由字典的值组成的字典视图。
>>> d = {'one': 1, 'two': 2 ,'three': 3, 'four': 4}
>>> d.keys()
dict_keys(['one', 'two', 'three', 'four'])
>>> d.values()
dict_values([1, 2, 3, 4])
网友评论