13
16

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.

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

Last updated at Posted at 2017-04-24

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

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']

13
16
4

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
13
16

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?