Convert nested dictionary into a dictionary

后端 未结 2 1012
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-21 10:00

I have a list of dictionary like this

[
 {\'id\':1, \'name\': \'name1\', \'education\':{\'university\':\'university1\', \'subject\': \'abc1\'}},
 {\'id\':2, \'na         


        
相关标签:
2条回答
  • 2021-01-21 10:25

    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'}] 
    
    0 讨论(0)
  • 2021-01-21 10:25

    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. If the size of the data is big, a solution including generators should be prefered.

    0 讨论(0)
提交回复
热议问题