首页 > 解决方案 > 无法将具有 int 类型键的 dict 分配给 EasyDict

问题描述

我使用EasyDict并想为其分配一个dictwith 类型的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我想要的我该怎么办,谢谢

标签: pythondictionary

解决方案


这是因为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'

推荐阅读