如何将 defaultdict 转换为 dict? [英] How to convert defaultdict to dict?
问题描述
如何转换 defaultdict
number_to_letterdefaultdict(, {'2': ['a'], '3': ['b'], '1': ['b', 'a']})
成为一个普通的dict
?
{'2': ['a'], '3': ['b'], '1': ['b', 'a']}
你可以直接调用dict
:
但请记住,defaultdict是一个dict:
<预><代码>>>>isinstance(a, dict)真的只是行为略有不同,因为当您尝试访问丢失的密钥时——这通常会引发 KeyError
——而是调用 default_factory
:
这就是你在字典的数据端出现之前打印一个
时看到的.
因此,在不实际创建新对象的情况下获得更多类似dict的行为的另一个技巧是重置default_factory
:
但大多数时候这不值得麻烦.
How can I convert a defaultdict
number_to_letter
defaultdict(<class 'list'>, {'2': ['a'], '3': ['b'], '1': ['b', 'a']})
to be a common dict
?
{'2': ['a'], '3': ['b'], '1': ['b', 'a']}
You can simply call dict
:
>>> a
defaultdict(<type 'list'>, {'1': ['b', 'a'], '3': ['b'], '2': ['a']})
>>> dict(a)
{'1': ['b', 'a'], '3': ['b'], '2': ['a']}
but remember that a defaultdict is a dict:
>>> isinstance(a, dict)
True
just with slightly different behaviour, in that when you try access a key which is missing -- which would ordinarily raise a KeyError
-- the default_factory
is called instead:
>>> a.default_factory
<type 'list'>
That's what you see when you print a
before the data side of the dictionary appears.
So another trick to get more dictlike behaviour back without actually making a new object is to reset default_factory
:
>>> a.default_factory = None
>>> a[4].append(10)
Traceback (most recent call last):
File "<ipython-input-6-0721ca19bee1>", line 1, in <module>
a[4].append(10)
KeyError: 4
but most of the time this isn't worth the trouble.
这篇关于如何将 defaultdict 转换为 dict?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!