簡體   English   中英

將嵌套字典轉換成字典

[英]Convert nested dictionary into a 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':'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'},
]

有沒有什么Python的方式來解決這個問題。

您可以簡單地執行以下操作:

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)

如您所見,flattenReturn會生成一個新的字典,該字典將字典中的值過濾掉,然后使用其鍵值對其進行更新以使其平坦化,而第二個選項會修改字典。 如果數據量很大,則應首選包含生成器的解決方案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM