简体   繁体   English

将嵌套字典转换为元组列表

[英]Convert a nested dictionary into list of tuples

I have a dictionary -我有一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 -我想把它转换成tuples list -

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

I tried using list comprehensions , but did not help -我尝试使用list comprehensions ,但没有帮助 -

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?有什么建议?

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.友情提示:在 Python 3.6 之前,不维护 dict 顺序。

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

您可以遍历字典的级别:

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

You can do it using a list comprehension, but it would be quite complex, and not easy to maintain if the structure changes.您可以使用列表推导式来完成,但它会非常复杂,如果结构发生变化,也不容易维护。 Unless you especially need good performance, I would suggest using a generic recursive function:除非您特别需要良好的性能,否则我建议使用通用递归函数:

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

As a bonus, I've also supported lists and tuples during the recursion, in addition to the set on the provided example.作为奖励,除了提供的示例中的集合之外,我还在递归期间支持列表和元组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM