如何将 defaultdict 转换为 dict? [英] How to convert defaultdict to dict?

查看:88
本文介绍了如何将 defaultdict 转换为 dict?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何转换 defaultdict

number_to_letterdefaultdict(, {'2': ['a'], '3': ['b'], '1': ['b', 'a']})

成为一个普通的dict?

{'2': ['a'], '3': ['b'], '1': ['b', 'a']}

解决方案

你可以直接调用dict:

<预><代码>>>>一种defaultdict(, {'1': ['b', 'a'], '3': ['b'], '2': ['a']})>>>字典(一){'1':['b','a'],'3':['b'],'2':['a']}

但请记住,defaultdict一个dict:

<预><代码>>>>isinstance(a, dict)真的

只是行为略有不同,因为当您尝试访问丢失的密钥时——这通常会引发 KeyError——而是调用 default_factory:

<预><代码>>>>a.default_factory<输入列表">

这就是你在字典的数据端出现之前打印一个时看到的.

因此,在不实际创建新对象的情况下获得更多类似dict的行为的另一个技巧是重置default_factory:

<预><代码>>>>a.default_factory = 无>>>a[4].append(10)回溯(最近一次调用最后一次):文件<ipython-input-6-0721ca19bee1>",第 1 行,在 <module> 中a[4].append(10)密钥错误:4

但大多数时候这不值得麻烦.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆