编写具有超过 2 个嵌套字典的 csv

发布于 2025-01-12 01:38:46 字数 591 浏览 0 评论 0原文

这是我的示例字典:

nested_dict = 
{
  "value1_1": "X",
  "value1_2": {
             "value2_1": "Y",
             "value2_2": {
                       "value3_1": "Z3_1",
                       "value3_2": "Z3_2"
                        ...
                        }
             ...
  }

我想将其转换为具有类似形式的 CSV:

X,Y,Z3_1,Z3_2

或者使用标题,但不希望有它:

Value1_1,Value2_1,Value3_1,Value3_2
X,Y,Z3_1,Z3_2

我找到了使用 DictWriter 的一些答案,但我不认为它支持超过 2 个嵌套字典。

我应该编写自己的 csv writer 吗?

Here is my sample dict:

nested_dict = 
{
  "value1_1": "X",
  "value1_2": {
             "value2_1": "Y",
             "value2_2": {
                       "value3_1": "Z3_1",
                       "value3_2": "Z3_2"
                        ...
                        }
             ...
  }

I want to convert it to a CSV with a similar form:

X,Y,Z3_1,Z3_2

Or with the header but would prefer not having it:

Value1_1,Value2_1,Value3_1,Value3_2
X,Y,Z3_1,Z3_2

I've found some answers with using DictWriter but I couldn't figure it supporting more than 2 nested dict.

Should I write my own csv writer?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

她如夕阳 2025-01-19 01:38:46

我认为你不会找到一个作家这样做。也许做这样的事情?

nested_dict = {
   "value1_1": "X",
   "value1_2": {
       "value2_1": "Y",
       "value2_2": {
           "value3_1": "Z3_1",
           "value3_2": "Z3_2"
       }
   }
}   

def getLatestLevel(dictionary, values=[]):
    for key, item in dictionary.items():
        if type(item) is dict:
            values = getLatestLevel(item, values)
        else:
            values.append(item)
    return values
            

with open("FILE.csv", 'w') as myfile:
    myfile.write(", ".join(getLatestLevel(nested_dict)))

它会将其写入FILE.csv

X, Y, Z3_1, Z3_2

I do not think that you will find a writer doing that. Maybe do something like this?

nested_dict = {
   "value1_1": "X",
   "value1_2": {
       "value2_1": "Y",
       "value2_2": {
           "value3_1": "Z3_1",
           "value3_2": "Z3_2"
       }
   }
}   

def getLatestLevel(dictionary, values=[]):
    for key, item in dictionary.items():
        if type(item) is dict:
            values = getLatestLevel(item, values)
        else:
            values.append(item)
    return values
            

with open("FILE.csv", 'w') as myfile:
    myfile.write(", ".join(getLatestLevel(nested_dict)))

It will write this to FILE.csv:

X, Y, Z3_1, Z3_2
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文