python:dict
차이
문서의 선택한 두 판 사이의 차이를 보여줍니다.
양쪽 이전 판이전 판다음 판 | 이전 판 | ||
python:dict [2024/01/19 00:20] – 제거됨 - 바깥 편집 (Unknown date) 127.0.0.1 | python: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 = {' | ||
+ | ' | ||
+ | ' | ||
+ | |||
+ | df = pd.json_normalize(d, | ||
+ | |||
+ | print(df.to_dict(orient=' | ||
+ | |||
+ | # https:// | ||
+ | </ | ||
+ | |||
+ | |||
+ | * nested dict to object | ||
+ | |||
+ | <code python> | ||
+ | from types import SimpleNamespace | ||
+ | import json | ||
+ | |||
+ | |||
+ | class Config(SimpleNamespace): | ||
+ | def __init__(self, | ||
+ | super().__init__(**config_dict) | ||
+ | |||
+ | |||
+ | def dict2obj(d): | ||
+ | return json.loads(json.dumps(d), | ||
+ | | ||
+ | config_dict = {' | ||
+ | config = dict2obj(config_dict) | ||
+ | print(config.a) | ||
+ | |||
+ | # https:// | ||
+ | </ | ||
+ | |||
+ | * nested dict to namedtuple | ||
+ | |||
+ | <code python> | ||
+ | from collections import namedtuple | ||
+ | |||
+ | |||
+ | def make_config(cfg): | ||
+ | if isinstance(cfg, | ||
+ | return make_config_dict(cfg) | ||
+ | elif isinstance(cfg, | ||
+ | return make_config_list(cfg) | ||
+ | else: | ||
+ | raise NotImplementedError() | ||
+ | |||
+ | |||
+ | def make_config_dict(cfg): | ||
+ | Config = namedtuple(' | ||
+ | values = list() | ||
+ | for value in cfg.values(): | ||
+ | if isinstance(value, | ||
+ | value = make_config_dict(value) | ||
+ | elif isinstance(value, | ||
+ | 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, | ||
+ | value = make_config_dict(value) | ||
+ | elif isinstance(value, | ||
+ | value = make_config_list(value) | ||
+ | values.append(value) | ||
+ | return values | ||
+ | | ||
+ | config_dict = {' | ||
+ | config = make_config(config_dict) | ||
+ | print(config) | ||
+ | </ | ||
+ | |||
+ | {{tag> | ||
+ | |||