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

时间:2019-08-23 13:39:58

标签: python tuples dictionary-comprehension

我有一个dictionary-

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

我想将其转换为list中的tuples-

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

我尝试使用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'})])]

有什么建议吗?

3 个答案:

答案 0 :(得分:3)

如果您不确定此列表可能有多少级,似乎您需要的是递归:

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

谨此提醒您:在Python 3.6之前,不维护dict顺序。

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

答案 1 :(得分:1)

您可以循环浏览字典的各个级别:

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

答案 2 :(得分:0)

您可以使用列表推导式来完成,但它会非常复杂,如果结构发生变化,也不容易维护。 除非您特别需要良好的性能,否则我建议使用通用递归函数:

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

作为奖励,除了提供的示例中的集合之外,我还在递归期间支持列表和元组。