将嵌套字典转换为字典

5
我有一个像这样的字典列表
[
 {'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'},
]

有没有Pythonic的方法来解决这个问题。


1
{btsdaf} - Ashish Ranjan
1
https://docs.python.org/2/library/functions.html#map - c69
2个回答

9
您可以简单地执行以下操作:
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'}] 

{btsdaf} - R.A.Munna
{btsdaf} - user2390182

1

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

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)

正如您所看到的,flattenReturn 生成一个新的字典,过滤值为字典的键值对,然后使用它们的键值对来更新它以使其扁平化,而第二个选项则直接在原字典上进行修改。如果数据大小较大,则应优先选择包括生成器的解决方案。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接