辞書型のメソッド
>>> d = {'x': 10, 'y': 20}
>>> d
{'x': 10, 'y': 20}
help
>>> help(d)
Help on dict object:
class dict(object)
| dict() -> new empty dictionary
| dict(mapping) -> new dictionary initialized from a mapping object's
| (key, value) pairs
| dict(iterable) -> new dictionary initialized as if via:
| d = {}
| for k, v in iterable:
| d[k] = v
| dict(**kwargs) -> new dictionary initialized with the name=value pairs
| in the keyword argument list. For example: dict(one=1, two=2)
|
-- More --
keys
>>> d.keys()
dict_keys(['x', 'y'])
values
>>> d.values()
dict_values([10, 20])
update
>>> d2 = {'x': 1000, 'j': 500}
>>> d
{'x': 10, 'y': 20}
>>> d2
{'x': 1000, 'j': 500}
>>> d.update(d2)
>>> d
{'x': 1000, 'y': 20, 'j': 500}
値valueの取得
>>> d['x']
1000
get
>>> d.get('x')
1000
NoneType
>>> d['z']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'z'
>>> d.get('z')
>>> r = d.get('z')
>>> r
>>> type(r)
<class 'NoneType'>
削除
pop
>>> d
{'x': 1000, 'y': 20, 'j': 500}
>>> d.pop('x')
1000
>>> d
{'y': 20, 'j': 500}
del
>>> d
{'y': 20, 'j': 500}
>>> del d['y']
>>> d
{'j': 500}
>>> del d
>>> d
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'd' is not defined
clear
>>> d = {'a': 100, 'b': 200}
>>> d
{'a': 100, 'b': 200}
>>> d.clear()
>>> d
{}
判定
in
>>> d = {'a': 100, 'b':200}
>>> d
{'a': 100, 'b': 200}
>>> 'a' in d
True
>>> 'j' in d
False
コメント