1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Python 多次元 dict/collections.Mapping のキーを list に変換する

Last updated at Posted at 2018-12-16

辞書の要素に辞書を持つような多次元辞書のキーをリスト化する。
親要素のキーと子要素のキーを連結する。

イメージは以下。

# 変換元
{
    '': {
        '子1': 1,
        '子2': [1, 2, 3, 4],
        '子3': {
            '孫1': 1,
            '孫2': 2,
            '孫3': 3
        }
    }
}

# 変換結果
[
    '親.子1',
    '親.子2',
    '親.子3.孫1',
    '親.子3.孫2',
    '親.子3.孫3'
]

前提条件

  • OS: CentOS Linux release 7.5.1804 (Core)
  • Python: Python 3.6.5

ソースコード

import collections
import sys
import json


def convert_dict_to_list(dict_, path_delimiter='.', path=''):
    """dict/collections.Mappingをlistに変換する。

    Args:
        dict_ (dict or collections.Mapping): 変換元。
        path_delimiter (str): 多次元構造の場合の区切り。
        path (str): 値名に付与する文字列。

    Returns:
        list: 変換結果。
    """

    list_ = []
    is_top = len(path) == 0

    for k, v in dict_.items():
        if is_top:
            str_ = k
        else:
            str_ = '{}{}{}'.format(path, path_delimiter, k)

        if isinstance(v, dict) or isinstance(v, collections.Mapping):
            list_.extend(convert_dict_to_list(
                    v,
                    path_delimiter,
                    str_))
        else:
            list_.append(str_)

    return list_


def main():
    with open(sys.argv[1]) as f:
        json_data = json.load(f)

    list_ = convert_dict_to_list(json_data)
    print(list_)


if __name__ == '__main__':
    main()

実行サンプル

元データ(JSON文字列)

{
  "grp1": {
    "param1": "aaa",
    "param2": "bbb",
    "param3": 10,
    "param4": true,
    "param5": false,
    "grp1-1": {
      "param11": "aaa",
      "param12": "bbb",
      "param13": 10,
      "param14": true,
      "param15": false
    }
  }
}

変換結果

['grp1.param1', 'grp1.param2', 'grp1.param3', 'grp1.param4', 'grp1.param5', 'grp1.grp1-1.param11', 'grp1.grp1-1.param12', 'grp1.grp1-1.param13', 'grp1.grp1-1.param14', 'grp1.grp1-1.param15']
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?