字典————python 文档学习
python标准库: dict.
python教程: link.
python教程: link.
迭代器: link.
作为演示,以下示例返回的字典均等于{"one": 1, "two": 2, "three": 3}:
理解字典的最好方式,就是将它看做是一个 键: 值 对的集合,键必须是唯一的(在一个字典中)。一对花括号可以创建一个空字典:{} 。另一种初始化字典的方式是在一对花括号里放置一些以逗号分隔的键值对,而这也是字典输出的方式。
1. 创建字典方式
>>> 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})
对一个字典执行 list(d) 将返回包含该字典中所有键的列表,按插入次序排列 (如需其他排序,则要使用 sorted(d))。要检查字典中是否存在一个特定键,可使用 in 关键字。
2. 小例子
>>> tel = {'jack': 4098, 'sape': 4139}
>>> tel['guido'] = 4127
>>> tel
{'jack': 4098, 'sape': 4139, 'guido': 4127}
>>> tel['jack']
4098
>>> del tel['sape']
>>> tel['irv'] = 4127
>>> tel
{'jack': 4098, 'guido': 4127, 'irv': 4127}
>>> list(tel)
['jack', 'guido', 'irv']
>>> sorted(tel)
['guido', 'irv', 'jack']
>>> 'guido' in tel
True
>>> 'jack' not in tel
False
将 dict[key] 从 dict 中移除。 如果映射中不存在 key 则会引发 KeyError。
3. dict()构造函数小技巧
dict() 构造函数可以直接从键值对序列里创建字典。
>>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
{'sape': 4139, 'guido': 4127, 'jack': 4098}
>>> dict(sape=4139, guido=4127, jack=4098)
{'sape': 4139, 'guido': 4127, 'jack': 4098}
此外,字典推导式可以从任意的键值表达式中创建字典
>>> {x: x**2 for x in (2, 4, 6)}
{2: 4, 4: 16, 6: 36}
4.循环技巧
当在字典中循环时,用 items() 方法可将关键字和对应的值同时取出
>>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
>>> for k, v in knights.items():
... print(k, v)
...
gallahad the pure
robin the brave
当在序列中循环时,用 enumerate() 函数可以将索引位置和其对应的值同时取出
>>> for i, v in enumerate(['tic', 'tac', 'toe']):
... print(i, v)
...
0 tic
1 tac
2 toe
当同时在两个或更多序列中循环时,可以用 zip() 函数将其内元素一一匹配。
>>> questions = ['name', 'quest', 'favorite color']
>>> answers = ['lancelot', 'the holy grail', 'blue']
>>> for q, a in zip(questions, answers):
... print('What is your {0}? It is {1}.'.format(q, a))
...
What is your name? It is lancelot.
What is your quest? It is the holy grail.
What is your favorite color? It is blue.
如果要逆向循环一个序列,可以先正向定位序列,然后调用 reversed() 函数(内置函数reversed)
>>> for i in reversed(range(1, 10, 2)):
... print(i)
...
9
7
5
3
1
如果要按某个指定顺序循环一个序列,可以用 sorted() 函数,它可以在不改动原序列的基础上返回一个新的排好序的序列
>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
>>> for f in sorted(set(basket)):
... print(f)
...
apple
banana
orange
pear
有时可能会想在循环时修改列表内容,一般来说改为创建一个新列表是比较简单且安全的
>>> import math
>>> raw_data = [56.2, float('NaN'), 51.7, 55.3, 52.5, float('NaN'), 47.8]
>>> filtered_data = []
>>> for value in raw_data:
... if not math.isnan(value):
... filtered_data.append(value)
...
>>> filtered_data
[56.2, 51.7, 55.3, 52.5, 47.8]
5 for 语句
Python 中的 for 语句与你在 C 或 Pascal 中所用到的有所不同。 Python 中的 for 语句并不总是对算术递增的数值进行迭代(如同 Pascal),或是给予用户定义迭代步骤和暂停条件的能力(如同 C),而是对任意序列进行迭代(例如列表或字符串),条目的迭代顺序与它们在序列中出现的顺序一致。 例如(此处英文为双关语):
>>> # Measure some strings:
... words = ['cat', 'window', 'defenestrate']
>>> for w in words:
... print(w, len(w))
...
cat 3
window 6
defenestrate 12
在遍历同一个集合时修改该集合的代码可能很难获得正确的结果。通常,更直接的做法是循环遍历该集合的副本或创建新集合:
# Strategy: Iterate over a copy
for user, status in users.copy().items():
if status == 'inactive':
del users[user]
# Strategy: Create a new collection
active_users = {}
for user, status in users.items():
if status == 'active':
active_users[user] = status
例子实现:
# Strategy: Iterate over a copy
d = {"one": 1, "two": 2, "three": 3, "four": 4}
# Strategy: Iterate over a copy
for key, value in d.copy().items():
if value == 1:
del d[key]
for key,values in d.items():
print(key , values )
## Strategy: Iterate over a copy
#result
two 2
three 3
four 4
# Strategy: Create a new collection
d = {"one": 1, "two": 2, "three": 3, "four": 4}
active_users = {}
for key, value in d.items():
if key == "one":
active_users[key] = value
for key,values in active_users.items():
print(key , values )
#result:
one 1
6 迭代器:
在python中列表,元组等都是可迭代对象,我们可以通过iter()函数获取这些可迭代对象的迭代器。然后我们可以对获取到的迭代器不断使⽤next()函数来获取下⼀条数据。iter()函数实际上就是调⽤了可迭代对象的__iter__方法(注意是两个横线,简单来说就是类似于C语言中的对链表结构的遍历,当指针不为空时就一直遍历下去,不停迭代。
7 这些是字典所支持的操作(因而自定义的映射类型也应当支持):
- list(d)
返回字典 d 中使用的所有键的列表。
>>> d = {"one": 1, "two": 2, "three": 3, "four": 4}
>>> d
{'one': 1, 'two': 2, 'three': 3, 'four': 4}
>>> list(d)
['one', 'two', 'three', 'four']
>>> list(d.values())
[1, 2, 3, 4]
- len(d)
返回字典 d 中的项数。
len(d)
Out[71]: 4
- d[key] = value
当插入新的键值对时,作用相当于列表中添加元素的函数append()
d
Out[76]: {'one': 1, 'two': 2, 'three': 3, 'four': 4}
d['five']=5
d
Out[78]: {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5}
不仅如此,还可以,改变键对应的值
d['three']=9
d
Out[80]: {'one': 1, 'two': 2, 'three': 9, 'four': 4, 'five': 5}
-
d[key]
返回 d 中以 key 为键的项。 如果映射中不存在 key 则会引发 KeyError。 -
del d[key]
将d[key]
从 d 中移除。 如果映射中不存在 key 则会引发 KeyError。
>>> d
d
Out[89]: {'one': 1, 'two': 2, 'three': 3, 'four': 4}
del d['two']
d
Out[91]: {'one': 1, 'three': 3, 'four': 4}
d["two"] = None
d
Out[93]: {'one': 1, 'three': 3, 'four': 4, 'two': None}
-
key in d
如果 d 中存在键 key 则返回 True,否则返回 False。
-
key not in d
如果 d 中存在键 key 则返回 False,否则返回 true。
等价于 not key in d。
- iter(d)
返回以字典的键为元素的迭代器。 这是iter(d.keys())
的快捷方式。
d
Out[80]: {'one': 1, 'two': 2, 'three': 9, 'four': 4, 'five': 5}
it=iter(d)
next(it)
Out[82]: 'one'
next(it)
Out[83]: 'two'
next(it)
Out[84]: 'three'
next(it)
Out[85]: 'four'
# iter()。 该函数返回一个定义了 __next__() 方法的迭代器对象,
# 此方法将逐一访问容器中的元素。
-
copy()
返回原字典的浅拷贝。 -
items()
返回由字典项 ((键, 值) 对)
组成的一个新视图。 参见
视图对象文档: link.。 -
keys()
返回由字典键组成的一个新视图。 参见
视图对象文档: link.。 -
values()
返回由字典值组成的一个新视图。 参见
视图对象文档: link.。
#两个 dict.values() 视图之间的相等性比较将总是返回 False。
#这在 dict.values() 与其自身比较时也同样适用:
>>> d = {'a': 1}
>>> d.values() == d.values()
False
- pop(key[, default])
如果 key 存在于字典中则将其移除并返回其值,否则返回 default。 如果 default 未给出且 key 不存在于字典中,则会引发 KeyError。
d
Out[105]: {'one': 1, 'two': 2, 'three': 3, 'four': 4}
d.pop('two')
Out[106]: 2
d
Out[107]: {'one': 1, 'three': 3, 'four': 4}
- popitem()
从字典中移除并返回一个 (键, 值) 对。 键值对会按 LIFO(后进先出) 的顺序被返回。
d
Out[109]: {'one': 1, 'two': 2, 'three': 3, 'four': 4}
d.popitem()
Out[110]: ('four', 4)
d
Out[111]: {'one': 1, 'two': 2, 'three': 3}
- reversed(d)
这是 reversed(d.keys()) 的快捷方式
但是从3.7开始将保证字典键的严格顺序,下面的代码将错误
# TypeError: 'dict' object is not reversible
for k in reversed(d):
print(k)
# TypeError: 'dict_keys' object is not reversible
for k in reversed(d.keys()):
print(k)
#错误提示
'dict_keys' object is not reversible
修改成正确代码如下:
d = {"one": 1, "two": 2, "three": 3, "four": 4}
for k in reversed(list(d.keys())):
print(k)
#结果如下
four
three
two
one