简体   繁体   English

将嵌套字典转换成字典

[英]Convert nested dictionary into a dictionary

I have a list of dictionary like this 我有这样的字典清单

[
 {'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'}},
]

and I want to convert it like 我想将其转换为

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

is there any pythonic way to solve this. 有没有什么Python的方式来解决这个问题。

You could simply do the following: 您可以简单地执行以下操作:

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

Depending if you want to transform the original list or if you want to return a new one you could go for one of these two approaches: 根据您是要转换原始列表还是要返回新列表,可以采用以下两种方法之一:

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)

As you can see flattenReturn generates a new dict filtering the values which are dictionaries and then updates it with their key-values to flatten it while the second option modifies the dict in place. 如您所见,flattenReturn会生成一个新的字典,该字典将字典中的值过滤掉,然后使用其键值对其进行更新以使其平坦化,而第二个选项会修改字典。 If the size of the data is big, a solution including generators should be prefered. 如果数据量很大,则应首选包含生成器的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM