Python 将字典值展平

Python 将字典值展平,python,Python,我有一本这种格式的字典 {'column1': {'id': 'object'}, 'column2': {'mark': 'int64'}, 'column3': {'name': 'object'}, 'column4': {'distance': 'float64'}} 我希望将其转换为以下格式: {'id': 'object', 'mark': 'int64', 'name': 'object', 'distance': 'float64'} i、 在另一个放平的字典中记

我有一本这种格式的字典

{'column1': {'id': 'object'},
 'column2': {'mark': 'int64'},
 'column3': {'name': 'object'},
 'column4': {'distance': 'float64'}}
我希望将其转换为以下格式:

{'id': 'object',
 'mark': 'int64',
 'name': 'object',
 'distance': 'float64'}
i、 在另一个放平的字典中记录口述词的值

我尝试使用:

L= []
for i in d.values():
    L.append(str(i))
dict(L)

但是它不起作用。

像这样使用听写理解:

>>> my_dict = {'column1': {'id': 'object'},
 'column2': {'mark': 'int64'},
 'column3': {'name': 'object'},
 'column4': {'distance': 'float64'}}
>>> result = {k:v for d in my_dict.values() for k,v in  d.items()}
>>> result
{'distance': 'float64', 'mark': 'int64', 'id': 'object', 'name': 'object'}

如果您想了解当前解决方案不起作用的原因,那是因为您正在寻找一个字典作为最终结果,但它会附加到一个列表中。在循环内部,调用
dict.update

result = {}
for i in data.values():
    result.update(i)

print(result)
{'name': 'object', 'mark': 'int64', 'id': 'object', 'distance': 'float64'}

这可能是最简单的解决方案:

columns = {'column1': {'id': 'object'},
 'column2': {'mark': 'int64'},
 'column3': {'name': 'object'},
 'column4': {'distance': 'float64'}}

newColumns = {}
for key, value in columns.items():
  for newKey, newValue in value.items():
    newColumns[newKey] = newValue

print(newColumns)

就是这样!可能的重复我倾向于不同意。我认为
更新
要简洁得多,然后是前面答案所示的dict comp。