本文介绍了将嵌套字典转换为元组列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字典 -

d={'收入':{'201907':{'aaa.csv':'fdwe34x2'},'201906':{'ddd.csv':'e4c5q'}},投诉":{'2014':{'sfdwa.csv','c2c2jh'}}}

我想把它转换成tupleslist -

[('收入','201907','aaa.csv','fdwe34x2'),('收入','201906','ddd.csv','e4c5q'),('投诉','2014','sfdwa.csv','c2c2jh')]

我尝试使用 list comprehensions,但没有帮助 -

l = [(k,[(p,q) for p,q in v.items()]) for k,v in d.items()]打印(升)[('收入', [('201907', {'aaa.csv': 'fdwe34x2'}), ('201906', {'ddd.csv': 'e4c5q'})]),('投诉', [('2014', {'c2c2jh', 'sfdwa.csv'})])]

有什么建议吗?

解决方案

如果你不确定这个列表可能有多少级,看来你需要的是递归:

def unnest(d, keys=[]):结果 = []对于 d.items() 中的 k, v:如果 isinstance(v, dict):result.extend(unnest(v, keys + [k]))别的:result.append(tuple(keys + [k, v]))返回结果

友情提示:在 Python 3.6 之前,不维护字典顺序.

[('投诉', '2014', 'sfdwa.csv', 'c2c2jh'),('收入', '201906', 'ddd.csv', 'e4c5q'),(收入"、201907"、aaa.csv"、fdwe34x2")]

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?

解决方案

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

这篇关于将嵌套字典转换为元组列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 02:35