Python:将 defaultdict 转换为 dict

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20428636/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 20:24:39  来源:igfitidea点击:

Python: convert defaultdict to dict

pythondefaultdict

提问by user2988464

How can i convert a defaultdict

我如何转换 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']}

采纳答案by DSM

You can simply call dict:

您可以简单地调用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 isa dict:

但请记住,defaultdict一个 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_factoryis called instead:

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

>>> a.default_factory
<type 'list'>

That's what you see when you print abefore the data side of the dictionary appears.

这就是您print a在字典的数据侧出现之前所看到的。

So another trick to get more dictlike behaviour back without actually making a new object is to reset default_factory:

因此,在不实际创建新对象的情况下获得更多类似 dict 行为的另一个技巧是重置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.

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

回答by white_gecko

If you even want a recursive version for converting a recursive defaultdictto a dictyou can try the following:

如果你连想一个递归版本的递归转换defaultdict到一个dict你可以尝试以下方法:

#! /usr/bin/env python3

from collections import defaultdict

def ddict():
    return defaultdict(ddict)

def ddict2dict(d):
    for k, v in d.items():
        if isinstance(v, dict):
            d[k] = ddict2dict(v)
    return dict(d)

myddict = ddict()

myddict["a"]["b"]["c"] = "value"

print(myddict)

mydict = ddict2dict(myddict)

print(mydict)

回答by Meow

If your defaultdict is recursively defined, for example:

如果您的 defaultdict 是递归定义的,例如:

from collections import defaultdict
recurddict = lambda: defaultdict(recurddict)
data = recurddict()
data["hello"] = "world"
data["good"]["day"] = True

yet another simple way to convert defaultdict back to dict is to use jsonmodule

将 defaultdict 转换回 dict 的另一种简单方法是使用jsonmodule

import json
data = json.loads(json.dumps(data))

and of course, the values contented in your defaultdict need to be confined to json supported data types, but it shouldn't be a problem if you don't intent to store classes or functions in the dict.

当然,您的 defaultdict 中包含的值需要限于 json 支持的数据类型,但如果您不打算在 dict 中存储类或函数,这应该不是问题。