Python 在嵌套的dict中连接字符串

Python 在嵌套的dict中连接字符串,python,python-3.x,Python,Python 3.x,我在下面写了一段话: { 1:{1:{'text':'Contact','x0':十进制('223.560')}, 2:{1:{'text':'myemail','x0':十进制('223.560')}, 2:{'text':'is','x0':十进制('279.552'), 3:{'text':'domain@example.com','x0':十进制('290.868')} } 每个dict对应一行,每个嵌套dict对应该行上的一个单词/一系列单词 我正在尝试转换它,使每个dict等于一行

我在下面写了一段话:

{
1:{1:{'text':'Contact','x0':十进制('223.560')},
2:{1:{'text':'myemail','x0':十进制('223.560')},
2:{'text':'is','x0':十进制('279.552'),
3:{'text':'domain@example.com','x0':十进制('290.868')}
}
每个dict对应一行,每个嵌套dict对应该行上的一个单词/一系列单词

我正在尝试转换它,使每个dict等于一行,其中单词被连接起来,并且键被更改为
row

预期产出:

 1: {'row': 'Contact'},
 2: {'row': 'My email is domain@example.com'}
我不知道该怎么做?有人能指导我正确的纠正吗?

看起来你需要

from decimal import Decimal
d = {
 1: {1: {'text': 'Contact', 'x0': Decimal('223.560')}},
 2: {1: {'text': 'My email', 'x0': Decimal('223.560')},
     2: {'text': 'is', 'x0': Decimal('279.552')},
     3: {'text': 'domain@example.com', 'x0': Decimal('290.868')}
    }
}

result = {}
for k, v in d.items():
    result[k] = {"row": " ".join(n["text"] for _, n in v.items())}       
print(result)
输出:

{1: {'row': 'Contact'}, 2: {'row': 'My email is domain@example.com'}}
看来你需要

from decimal import Decimal
d = {
 1: {1: {'text': 'Contact', 'x0': Decimal('223.560')}},
 2: {1: {'text': 'My email', 'x0': Decimal('223.560')},
     2: {'text': 'is', 'x0': Decimal('279.552')},
     3: {'text': 'domain@example.com', 'x0': Decimal('290.868')}
    }
}

result = {}
for k, v in d.items():
    result[k] = {"row": " ".join(n["text"] for _, n in v.items())}       
print(result)
输出:

{1: {'row': 'Contact'}, 2: {'row': 'My email is domain@example.com'}}

您可以使用一个简单的列表:

d = {1: {1: {'text': 'Contact', 'x0': Decimal('223.560')}}, 2: {1: {'text': 'My email', 'x0': Decimal('223.560')}, 2: {'text': 'is', 'x0': Decimal('279.552')}, 3: {'text': 'domain@example.com', 'x0': Decimal('290.868')}}} 
new_d = {a:{'row':' '.join(i['text'] for i in b.values())} for a, b in d.items()}
输出:

{1: {'row': 'Contact'}, 2: {'row': 'My email is domain@example.com'}}

您可以使用一个简单的列表:

d = {1: {1: {'text': 'Contact', 'x0': Decimal('223.560')}}, 2: {1: {'text': 'My email', 'x0': Decimal('223.560')}, 2: {'text': 'is', 'x0': Decimal('279.552')}, 3: {'text': 'domain@example.com', 'x0': Decimal('290.868')}}} 
new_d = {a:{'row':' '.join(i['text'] for i in b.values())} for a, b in d.items()}
输出:

{1: {'row': 'Contact'}, 2: {'row': 'My email is domain@example.com'}}

为什么将钥匙命名为“行”?请向我们展示您的尝试。为什么将钥匙命名为“行”?请向我们展示您的尝试。