我有下面的嵌套字典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/