python - 将嵌套的字典项合并到一个字符串中

标签 python python-3.x

我有下面的嵌套字典d:

{
 1: {1: {'text': 'Contact', 'x0': Decimal('21.600')}},
 2: {1: {'text': 'My mail is', 'x0': Decimal('21.600')},
     2: {'text': 'domain@example.com', 'x0': Decimal('223.560')}}
}

我试图将每个顶级键的嵌套字典“组合”成一个字符串(应该形成一个句子)。例如:

1: Contact
2: My mail is domain@example.com

所以我对如何在 Python 中做到这一点有点疑问。这是我目前拥有的:

for line in d:
    for word_no, text in d[line].items():
        print(text['text'])

这会打印每个text字符串,但不会组合任何内容。谁能引导我走向正确的方向?

最佳答案

您只需要另一次迭代。

例如:

from decimal import Decimal

d = {
 1: {1: {'text': 'Contact', 'x0': Decimal('21.600')}},
 2: {1: {'text': 'My mail is', 'x0': Decimal('21.600')},
     2: {'text': 'domain@example.com', 'x0': Decimal('223.560')}}
}

for k, v in d.items():
    print("{}: {}".format(k, " ".join(n["text"] for _, n in v.items())))   #Combine "text"

输出:

1: Contact
2: My mail is domain@example.com

关于python - 将嵌套的字典项合并到一个字符串中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56832344/

相关文章:

python - 如何在不创建新文件的情况下使用 ffmpeg/avconv 更改元数据?

python - 大数据集上 numpy polyfit 的解读

python - 使用递归函数处理构建字符串

python - 从以前的字段向 NamedTuple 添加字段

python-3.x - Early Stopping,模型经历了多少个epoch?

python用整数替换列表中的字符串

python-3.x - 使用 lambda 函数作为排序的键

python - 如何将用户添加到资格

Python:如何导入与子包同名的模块?

python - 显示创建的新网页的链接