Python 将嵌套字典转换为字典

Python 将嵌套字典转换为字典,python,dictionary,Python,Dictionary,我有一本这样的字典 [ {'id':1, 'name': 'name1', 'education':{'university':'university1', 'subject': 'abc1'}}, {'id':2, 'name': 'name2', 'education':{'university':'university2', 'subject': 'abc2'}}, {'id':3, 'name': 'name3', 'education':{'university':'univer

我有一本这样的字典

[
 {'id':1, 'name': 'name1', 'education':{'university':'university1', 'subject': 'abc1'}},
 {'id':2, 'name': 'name2', 'education':{'university':'university2', 'subject': 'abc2'}},
 {'id':3, 'name': 'name3', 'education':{'university':'university3', 'subject': 'abc3'}},
]
我想把它转换成

[
 {'id':1, 'name': 'name1', 'university':'university1', 'subject': 'abc1'},
 {'id':2, 'name': 'name2', 'university':'university2', 'subject': 'abc2'},
 {'id':3, 'name': 'name3', 'university':'university3', 'subject': 'abc3'},
]

有没有什么办法可以解决这个问题

您可以简单地执行以下操作:

l = [...]

for d in l:
   d.update(d.pop('education', {}))

# l
[{'id': 1, 'name': 'name1', 'subject': 'abc1', 'university': 'university1'},
 {'id': 2, 'name': 'name2', 'subject': 'abc2', 'university': 'university2'},
 {'id': 3, 'name': 'name3', 'subject': 'abc3', 'university': 'university3'}] 

根据您是要转换原始列表还是要返回新列表,您可以选择以下两种方法之一:

l = [
 {'id':1, 'name': 'name1', 'education':{'university':'university1', 'subject': 'abc1'}},
 {'id':2, 'name': 'name2', 'education':{'university':'university2', 'subject': 'abc2'}},
 {'id':3, 'name': 'name3', 'education':{'university':'university3', 'subject': 'abc3'}},
]

def flattenReturn(input):
    output = {key: value for key, value in input.items() if type(value) != dict}
    for value in input.values():
        if type(value) == dict:
            output.update(value)
    return output

def flattenTransform(d):
    for key, value in list(d.items()):
        if isinstance(value, dict):
            d.update(d.pop(key))

print(list(map(flattenReturn, l)))
print(l)
print("-"*80)
map(flattenTransform, l)
print(l)

正如您所看到的,FlattReturn生成一个新的dict,过滤字典中的值,然后用它们的键值更新它以将其展平,同时第二个选项修改dict。如果数据量较大,则应首选包含生成器的解决方案。

这是实际数据还是子目录中有更多子目录?工作正常:)。那嵌套的字典呢+这是一个不同的问题:)一个在这些海岸上被问了很多次的问题。在谷歌上搜索“压扁嵌套的dicts”,你会发现很多答案。