Warm tip: This article is reproduced from stackoverflow.com, please click
dictionary python

Failed to assign a dict with key of type int to EasyDict

发布于 2020-03-29 21:00:51

I use EasyDict and want to assign a dict with key of type int to it

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!

How should I do if I wanna assign the dict I want, thanks

Questioner
Wilson
Viewed
73
493 2020-01-31 21:04

It is because EasyDict is converting any value of dict to an EasyDict. And making an attribute out of the keys. int values cannot be attributes so this won't work. You can install PermissiveDict, which does much the same as EasyDict but does not try to convert values to it's own type.

pip install permissive-dict

Your example:

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'