温馨提示:本文翻译自stackoverflow.com,查看原文请点击:python - Failed to assign a dict with key of type int to EasyDict
dictionary python

python - 无法将类型为int的键的字典分配给EasyDict

发布于 2020-03-29 21:43:43

我使用EasyDict和要指派一个dict类型的钥匙int

from easydict import EasyDict as edict
cfg = edict()
cfg.tt = {'0': 'aeroplane'}  # this is ok
cfg.tt = {0: 'aeroplane'}  # this raises error, but this is what I want to use!

我想分配dict我想要的东西怎么办,谢谢

查看更多

提问者
Wilson
被浏览
46
493 2020-01-31 21:04

这是因为要将的EasyDict任何值转换dictEasyDict并根据键创建属性。 int值不能是属性,因此这是行不通的。您可以安装PermissiveDict,它的作用与上一次相同,EasyDict但不会尝试将值转换为它自己的类型。

pip install permissive-dict

你的例子:

from permissive_dict import PermissiveDict
cfg = PermissiveDict()
cfg.tt = {'0': 'aeroplane'}  # this is ok
cfg.tt = {0: 'aeroplane'}  # this does not raise errors, but this is what I want to use!

cfg.tt[0]) == cfg.TT[0] == cfg.tT[0] == cfg.Tt[0] == 'aeroplane'