logo

EasyDict: A Python Package for Convenient Dictionary Use 📂Programing

EasyDict: A Python Package for Convenient Dictionary Use

Overview1

Introducing the easydict package that makes it convenient to use dictionaries. By using EasyDict within the package, you can access the values of a dictionary as if they were attributes, and this works recursively.

Code

A standard Python dictionary is defined as follows.

김채원 = {
    '국적': '대한민국',
    '나이': 22,
    '키': 163,
}

# 혹은
김채원 = {}

김채원['국적'] = '대한민국'
김채원['나이'] = 22
김채원['키'] = 163

To retrieve a value from the dictionary, you need to place the key inside the brackets as defined above. Here, if the key is not a number but a string, it must also have quotes, and it cannot be used as an attribute.

>>> 김채원['국적']
'대한민국'

>>> 김채원[나이]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name '나이' is not defined

>>> 김채원.키
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'dict' object has no attribute '키'

>>> 사쿠라 = { 국적: '일본'}
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name '국적' is not defined

With EasyDict, you can use it conveniently like this.

>>> from easydict import EasyDict as edict
>>>
>>> 김채원 = edict()
>>> 김채원.국적 = '대한민국'
>>> 김채원.키 = 163
>>> 김채원.나이 = 22

>>> 김채원.국적
'대한민국'

>>> 김채원.키
163

Especially, because it works recursively, it is useful when defining a dictionary within a dictionary.

>>> 르세라핌 = edict()
>>> 르세라핌.김채원 = edict()
>>> 르세라핌.사쿠라 = edict()
>>> 르세라핌.허윤진 = edict()
>>> 르세라핌.카즈하 = edict()
>>> 르세라핌.홍은채 = edict()
>>>
>>> 르세라핌.김채원.국적 = '대한민국'
>>> 르세라핌.김채원.키 = 163
>>> 르세라핌.김채원.나이 = 22
>>> 
>>> 르세라핌
{'김채원': {'국적': '대한민국', '키': 163, '나이': 22}, '사쿠라': {}, '허윤진': {}, '카즈하': {}, '홍은채': {}}

Environment

  • OS: Windows11
  • Version: Python 3.9.13, easydict==1.10