LoginSignup
2
2

More than 3 years have passed since last update.

【Python】Nestしたdictで特定の文字列を含むValueを見つける

Last updated at Posted at 2021-04-19

TL;TD

  • dictで特定の文字列を含むValueを見つけて、文字列加工を行いたかった
  • 結果はそのValueまでの文字列が格納されたlistが出力される
    • dict-keyの場合はkey名、listの場合はindexが文字列に含まれる
  • このままでは実際にValueにアクセスはできないので、実際にはdpathのモジュールを使用して値は取得する

  • こんな感じで指定の条件を満たすValueどこにあるか探す

    • list / str になるまで再帰的に処理を行う
  • list内にdictが含まれる場合が考慮されてないので、そこは要改良

def __get_dict_path_by_match_str_pattern(self, my_dict, pattern, path="", result=None):
        if result is None:
          result = []
        for key, value in my_dict.items():
            if isinstance(value, dict):
                self.__get_dict_path_by_match_str_pattern(value, pattern, "{}/{}".format(path, key), result)
            elif isinstance(value, (list, tuple)):
                result += ["{}/{}/{}".format(path, key, i) for i, v in enumerate(value) if pattern in v]
            elif isinstance(value, (str, int)):
                if pattern in value:
                    result.append("{}/{}".format(path, key))
            else:
                raise ValueError("Not support type {}. Value is {}".format(type(value), value))
        return result

Ex.

Valueに"l" を含む文字列を持つものを探す

input

{
  "attr": {
    "types": {
      "tag": {
        "name": "Tom",
        "gender": "male"
      },
      "category": "employee"
    }
  }
}

output

["/attr/types/tag/gender", "/attr/types/category/0"]

感想

  • yieldとか使うともっと効率よく処理できそう。今度試そう
2
2
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
2
2