gpt4 book ai didi

python - 返回嵌套字典中的所有键以及值

转载 作者:太空宇宙 更新时间:2023-11-03 16:18:59 25 4
gpt4 key购买 nike

我正在努力将多个 .yaml 文件中存在的所有文本放入一个新的单一 YAML 文件中,该文件将包含英语翻译,然后有人可以将其翻译成西类牙语。

每个 YAML 文件都有大量嵌套文本。我想打印 YAML 文件中每个值的完整“路径”(也称为所有键)以及值。以下是位于 myproject.section.more_information 文件中的 .yaml 文件的示例输入:

default: 
heading: Here’s A Title
learn_more:
title: Title of Thing
url: www.url.com
description: description
opens_new_window: true

这是所需的输出:

myproject.section.more_information.default.heading: Here’s a Title
myproject.section.more_information.default.learn_more.title: Title of Thing
mproject.section.more_information.default.learn_more.url: www.url.com
myproject.section.more_information.default.learn_more.description: description
myproject.section.more_information.default.learn_more.opens_new_window: true

这似乎是递归的一个很好的候选者,所以我查看了诸如 this answer 之类的示例

但是,我想保留导致给定值的所有键,而不仅仅是值中的最后一个键。我目前正在使用 PyYAML 来读取/写入 YAML。

当我继续检查该项目是否是字典,然后返回与每个值关联的所有键时,有关如何保存每个键的任何提示?

最佳答案

您想要做的是展平嵌套字典。这将是一个很好的起点:Flatten nested Python dictionaries, compressing keys

事实上,我认为如果您只是将 sep 参数更改为 ,那么顶部答案中的代码片段将适合您。

编辑:

根据链接的 SO 答案检查此工作示例 http://ideone.com/Sx625B

import collections

some_dict = {
'default': {
'heading': 'Here’s A Title',
'learn_more': {
'title': 'Title of Thing',
'url': 'www.url.com',
'description': 'description',
'opens_new_window': 'true'
}
}
}

def flatten(d, parent_key='', sep='_'):
items = []
for k, v in d.items():
new_key = parent_key + sep + k if parent_key else k
if isinstance(v, collections.MutableMapping):
items.extend(flatten(v, new_key, sep=sep).items())
else:
items.append((new_key, v))
return dict(items)

results = flatten(some_dict, parent_key='', sep='.')
for item in results:
print(item + ': ' + results[item])

如果您希望按顺序排列,则需要一个 OrderedDict。

关于python - 返回嵌套字典中的所有键以及值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38668680/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com