展开字典值python

2024-04-26 04:06:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一本这种格式的词典。在

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

我希望将此转换为以下格式:

^{pr2}$

也就是说,在另一个扁平字典中听写词的值。在

我尝试使用:

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

但它不起作用。在


Tags: nameidobject格式词典distancemarkcolumn1
3条回答

像这样使用听写理解:

>>> 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'}

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

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.update。在

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

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

相关问题 更多 >

    热门问题