阅读文档dict.setdefault
:就像get
但如果密钥不存在,那么它也被设置:
>>> my_dict = {}
>>> my_dict.setdefault('some key', 'a value')
'a value'
>>> my_dict
{'some key': 'a value'}
>>> my_dict.get('some key2', 'a value2')
'a value2'
>>> my_dict
{'some key': 'a value'}
稍微修改一下你的例子:
>>> def what(*words):
... d = dict()
... for word in words:
... curr = d
... for letter in word:
... curr = curr.setdefault(letter, {})
... curr = curr.setdefault('.', '.')
... print 'curr is now: %r while d is %r' % (curr, d)
...
>>> what('foo')
curr is now: '.' while d is {'f': {'o': {'o': {'.': '.'}}}}
正如您所看到curr
的变化,因为setdefault
有时(在您的示例中总是)调用它时会创建一个新的dict
并将其设置为 的值curr
,而d
始终引用原始的dict
。如您所见,它在循环后被修改,因为它的值{'f': {'o': {'o': {'.': '.'}}}}
与{}
.
可能您的困惑是由于curr = curr.setdefault(letter, {})
总是创建一个new和empty dict
,然后将其分配给curr
(因此对于每个字母,您将嵌套级别添加到原始dict
而不是覆盖值)。
看到这个:
>>> my_dict = {}
>>> curr = my_dict
>>> for letter in 'foo':
... print 'my_dict is now %r. curr is now %r' % (my_dict, curr)
... curr = curr.setdefault(letter, {})
...
my_dict is now {}. curr is now {}
my_dict is now {'f': {}}. curr is now {}
my_dict is now {'f': {'o': {}}}. curr is now {}
>>> my_dict
{'f': {'o': {'o': {}}}}
正如您所看到的,每个级别my_dict
都有一个新的嵌套级别。
也许,但我只是猜测,你想获得类似的东西'foo' -> {'f': {}, 'o': {}}
,在这种情况下你应该这样做:
>>> my_dict = {}
>>> for letter in 'foo':
... my_dict.setdefault(letter, {})
...
>>> my_dict
{'o': {}, 'f': {}}