search
LoginSignup
16

More than 3 years have passed since last update.

posted at

updated at

入れ子dictの全keyを取得するメソッド

コメントによりスマートな書き方があるので、是非参考にしてください。

test= {"w": {"y":{"z":1}},"ww":1, "www":{"yy":1}}

def allkeys(a):
    keys = a.keys()
    values = a.values()

    t = []
    for v in values:
        if isinstance(v, dict):
            t.extend(allkeys(v))

    result = [i for i in keys]
    result.extend(t)
    return result

r = allkeys(test)
print(r)


実行結果
['ww', 'www', 'w', 'yy', 'y', 'z']


キー名に親のキーを付けた場合

test= {"w": {"y":{"z":1}},"ww":1, "www":{"yy":1}}

def parentnema(k, v):
    return k +"."+ v

def allkeys(a):
    keys = a.keys()
    values = a.values()

    t = []
    for k in keys:
        v = a.get(k)
        if isinstance(v, dict):
            t.extend(map(lambda z: k + "." + z, allkeys(v)))

    result = [i for i in keys]
    result.extend(t)
    return result

r = allkeys(test)
print(r)

実行結果
 ['ww', 'www', 'w', 'www.yy', 'w.y', 'w.y.z']

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
What you can do with signing up
16