Convert a nested dictionary into list of tuples

那年仲夏 提交于 2019-12-11 17:14:29

问题


I have a dictionary -

d={'revenues':
             {
              '201907':
                      {'aaa.csv':'fdwe34x2'},
              '201906':{'ddd.csv':'e4c5q'}
             },    
   'complaints':
             {'2014':
                    {'sfdwa.csv','c2c2jh'}
             }
  }

I want to convert it into list of tuples -

[
 ('revenues','201907','aaa.csv','fdwe34x2'),
 ('revenues','201906','ddd.csv','e4c5q'),
 ('complaints','2014','sfdwa.csv','c2c2jh')
]

I tried using list comprehensions, but did not help -

l = [(k,[(p,q) for p,q in v.items()]) for k,v in d.items()]
print(l)
    [('revenues', [('201907', {'aaa.csv': 'fdwe34x2'}), ('201906', {'ddd.csv': 'e4c5q'})]),
     ('complaints', [('2014', {'c2c2jh', 'sfdwa.csv'})])]

Any suggestions?


回答1:


If you're not sure how many levels this list may have, it seems that what you need is recursion:

def unnest(d, keys=[]):
    result = []
    for k, v in d.items():
        if isinstance(v, dict):
            result.extend(unnest(v, keys + [k]))
        else:
            result.append(tuple(keys + [k, v]))
    return result

Just a friendly reminder: before Python 3.6, dict order is not maintained.

[('complaints', '2014', 'sfdwa.csv', 'c2c2jh'),
 ('revenues', '201906', 'ddd.csv', 'e4c5q'),
 ('revenues', '201907', 'aaa.csv', 'fdwe34x2')]



回答2:


You can loop through the levels of your dictionary:

[(x, y, z) for x in d for y in d[x] for z in d[x][y]]


来源:https://stackoverflow.com/questions/57627575/convert-a-nested-dictionary-into-list-of-tuples

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!