사용자 도구

사이트 도구


python:dict

차이

문서의 선택한 두 판 사이의 차이를 보여줍니다.

차이 보기로 링크

양쪽 이전 판이전 판
다음 판
이전 판
python:dict [2024/01/19 00:20] – 제거됨 - 바깥 편집 (Unknown date) 127.0.0.1python:dict [2024/03/23 02:42] (현재) – 바깥 편집 127.0.0.1
줄 1: 줄 1:
 +====== Python: Dict ======
 +
 +  * nested dict to flatten dict
 +
 +<code python>
 +import pandas as pd
 +
 +d = {'a': 1,
 +     'c': {'a': 2, 'b': {'x': 5, 'y' : 10}},
 +     'd': [1, 2, 3]}
 +
 +df = pd.json_normalize(d, sep='.')
 +
 +print(df.to_dict(orient='records')[0])
 +
 +# https://stackoverflow.com/questions/6027558/flatten-nested-dictionaries-compressing-keys
 +</code>
 +
 +
 +  * nested dict to object
 +
 +<code python>
 +from types import SimpleNamespace
 +import json
 +
 +
 +class Config(SimpleNamespace):
 +    def __init__(self, config_dict):
 +        super().__init__(**config_dict)
 +
 +
 +def dict2obj(d):
 +    return json.loads(json.dumps(d), object_hook=Config)
 +    
 +config_dict = {'a': 1, 'b': {'c': 2}, 'd': ['hi', {'foo': 'bar'}]}
 +config = dict2obj(config_dict)
 +print(config.a)
 +
 +# https://stackoverflow.com/questions/1305532/convert-nested-python-dict-to-object
 +</code>
 +
 +  * nested dict to namedtuple
 +
 +<code python>
 +from collections import namedtuple
 +
 +
 +def make_config(cfg):
 +    if isinstance(cfg, dict):
 +        return make_config_dict(cfg)
 +    elif isinstance(cfg, list):
 +        return make_config_list(cfg)
 +    else:
 +        raise NotImplementedError()
 +
 +
 +def make_config_dict(cfg):
 +    Config = namedtuple('Config', cfg.keys())
 +    values = list()
 +    for value in cfg.values():
 +        if isinstance(value, dict):
 +            value = make_config_dict(value)
 +        elif isinstance(value, list):
 +            value = make_config_list(value)
 +        values.append(value)
 +    return Config(*values)
 +
 +
 +def make_config_list(cfg):
 +    values = list()
 +    for value in cfg:
 +        if isinstance(value, dict):
 +            value = make_config_dict(value)
 +        elif isinstance(value, list):
 +            value = make_config_list(value)
 +        values.append(value)
 +    return values
 +    
 +config_dict = {'a': 1, 'b': {'c': 2}, 'd': ['hi', {'foo': 'bar'}]}
 +config = make_config(config_dict)
 +print(config)
 +</code>
 +
 +{{tag>python dict}}
 +