星期三, 六月 20, 2007

python dict update

>>> zip(['a', 'b', 'c'], [1, 2, 3])
[('a', 1), ('b', 2), ('c', 3)]
>>> dict(zip(['a', 'b', 'c'], [1, 2, 3]))
{'a': 1, 'c': 3, 'b': 2}
>>> zip(['a', 'b', 'c'], [1, 2, 3], ['x', 'y', 'z'])
[('a', 1, 'x'), ('b', 2, 'y'), ('c', 3, 'z')]
>>> dict(zip(['a', 'b', 'c'], [1, 2, 3], ['x', 'y', 'z']))
Traceback (most recent call last):
File "", line 1, in ?
ValueError: dictionary update sequence element #0 has length 3; 2 is required
>>> help(dict.update)

>>> d = {'a' : 1, 'b' : 2, 'c': 3}
>>> print d
{'a': 1, 'c': 3, 'b': 2}
>>> d.update(('x', 'y', 'z'))
Traceback (most recent call last):
File "", line 1, in ?
ValueError: dictionary update sequence element #0 has length 1; 2 is required
>>> d.update(('x', 'y', 'z'), (4, 5, 6))
Traceback (most recent call last):
File "", line 1, in ?
TypeError: update expected at most 1 arguments, got 2
>>> d.update([('x', 4), ('y', 5), ('z', 6)])
>>> print d
{'a': 1, 'c': 3, 'b': 2, 'y': 5, 'x': 4, 'z': 6}
可见这里 d.update([('x', 4), ('y', 5), ('z', 6)]) 和 d.update({'x' : 4, 'y' : 5, 'z' : 6}) 拥有相同的效果。

没有评论: