映射类型-dict
映射类型-dict¶
字典的定义方式¶
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})
f = dict({'one': 1, 'three': 3}, two=2)
print(a == b == c == d == e == f)
字典的常用操作¶
1.d[key]¶
# 返回 d 中以 key 为键的项。 如果映射中不存在 key 则会引发 KeyError。
a = dict(one=1, two=2, three=3)
print(a["two"])
2
print(a["twoo"])
KeyError: 'twoo'
2.d[key] = value¶
# 将 d[key] 设为 value。
d = {'one': 1, 'two': 2, 'three': 3}
print(d['one'])
1
d['one'] = 10
print(d['one'])
10
3.del d[key]¶
# 将 d[key] 从 d 中移除。如果映射中不存在 key 则会引发 KeyError。
d = {'one': 1, 'two': 2, 'three': 3}
print(d)
del d['one']
print(d)
{'two': 2, 'one': 10, 'three': 3}
{'two': 2, 'three': 3}
del d['onee']
KeyError: 'onee'
字典的方法¶
1.get(key[, default])¶
# 如果 key 存在于字典中则返回 key 的值,否则返回 default。 如果 default 未给出则默认为 `None`,因而此方法绝不会引发 KeyError。
d = {'one': 1, 'two': 2, 'three': 3}
print(d.get('one'))
print(d.get('onee'))
print(d.get('onee',10))
1
None
10
setdefault(key[, default])¶
# 如果字典存在键 key ,返回它的值。如果不存在,插入值为 default 的键 key ,并返回 default 。default 默认为 `None`。
d = {'one': 1, 'two': 2, 'three': 3}
print(d.setdefault('one'))
print(d.setdefault('six'))
print(d.setdefault('four',42))
print(d)
1
None
42
{'one': 1, 'two': 2, 'three': 3, 'six': None, 'four': 42}
与
get
方法不同的是,setdefault
会在键不存在时添加该键到字典中。
2.keys()¶
# 返回由字典键组成的一个新视图。
d = {'one': 1, 'two': 2, 'three': 3}
for k in d.keys():
print(k)
one
two
three
3.values()¶
# 返回由字典值组成的一个新视图。
d = {'one': 1, 'two': 2, 'three': 3}
print(d.values())
dict_values([1, 2, 3])
for i in d.values():
print(i)
1
2
3
4.items()¶
# 返回由字典项 (`(键, 值)` 对) 组成的一个新视图。
d = {'one': 1, 'two': 2, 'three': 3}
for k,v in d.items():
print(k,v)
one 1
two 2
three 3
5.update([other])¶
# 使用来自 other 的键/值对更新字典,覆盖原有的键。 返回 `None`。
d = {'one': 1, 'two': 2, 'three': 3}
d1 = {'one': 10, 'name': 'jason'}
d.update(d1)
print(d)
{'one': 10, 'two': 2, 'three': 3, 'name': 'jason'}
6.clear()¶
# 移除字典中的所有元素。
d = {'one': 1, 'two': 2, 'three': 3}
d.clear()
print(d)
{}
7.pop(key[, default])¶
# 如果 *key* 存在于字典中则将其移除并返回其值,否则返回 *default*。 如果 *default* 未给出且 *key* 不存在于字典中,则会引发 KeyError。
d = {'one': 1, 'two': 2, 'three': 3}
d.pop('one')
print(d)
{'two': 2, 'three': 3}
8.popitem() 删除最后k,v¶
# 从字典中移除并返回一个 `(键, 值)` 对。 键值对会按 LIFO (后进先出)的顺序被返回。
d = {'one': 1, 'two': 2, 'three': 3}
d.popitem()
print(d)
{'one': 1, 'two': 2}
9.reversed(d)¶
# 返回一个逆序获取字典键的迭代器。 这是 `reversed(d.keys())` 的快捷方式。
d = {'one': 1, 'two': 2, 'three': 3}
for i in reversed(d):
print(i)
three
two
one
杂项¶
1、 list(d) 返回字典 d 中使用的所有键的列表。¶
a = dict(one=1, two=2, three=3)
print(list(a))
['one', 'two', 'three']
2、 len(d)返回字典 d 中的项数。¶
a = dict(one=1, two=2, three=3)
print(len(a))
3
3、 key in d 如果 d 中存在键 key 则返回 True
,否则返回 False
。¶
d = {'one': 1, 'two': 2, 'three': 3}
print('one' in d)
print('five' in d)
True
False
4、 key not in **d**等价于 not key in d
。¶
d = {'one': 1, 'two': 2, 'three': 3}
print('five' not in d)
print('one' not in d)
True
False
5、 iter(d)返回以字典的键为元素的迭代器。 这是 iter(d.keys())
的快捷方式。¶
d = {'one': 1, 'two': 2, 'three': 3}
for i in iter(d):
print(i)
one
two
three
6、 copy()返回原字典的浅拷贝。¶
d = {'one': 1, 'two': 2, 'three': 3}
print(d.copy())
print(id(d))
print(id(d.copy()))
{'one': 1, 'two': 2, 'three': 3}
2118555895488
2118555895680 # 浅拷贝不指向同一片内存地址
7、 classmethod fromkeys(iterable[, value])使用来自 iterable 的键创建一个新字典,并将键值设为 value。返回新字典的类方法。 value 默认为 None
。¶
d = {}
d = d.fromkeys(range(3),list(range(3)))
print(d)
{0: [0, 1, 2], 1: [0, 1, 2], 2: [0, 1, 2]}
合并字典¶
1、 d | other¶
# 合并 d 和 other 中的键和值来创建一个新的字典,两者必须都是字典。当 d 和 other 有相同键时, other 的值优先。
d = {'one': 1, 'two': 2, 'three': 3}
d1 = {'one': 10, 'two': 20, 'three': 30}
print(d | d1)
{'one': 10, 'two': 20, 'three': 30}
d = {'one': 1, 'two': 2, 'three': 3}
d1 = {'name': 'jason', 'age': 18}
print(d | d1)
{'one': 1, 'two': 2, 'three': 3, 'name': 'jason', 'age': 18}
2、 d |= other¶
# 用 other 的键和值更新字典 d ,other 可以是 [mapping] 或 [iterable]的键值对。当 d 和 other有相同键时, other 的值优先。
d = {'one': 1, 'two': 2, 'three': 3}
d1 = {'name': 'jason', 'age': 18}
d |= d1
print(d)
{'one': 1, 'two': 2, 'three': 3, 'name': 'jason', 'age': 18}
d = {'one': 1, 'two': 2, 'three': 3}
d1 = {'one': 10, 'two': 20, 'three': 30}
d |= d1
print(d)
{'one': 10, 'two': 20, 'three': 30}
# mapping
# iterable