[英]Python: Create new dictionary from list of dictionary
晚上好,我有這樣的清單:
start_list = [
{u'body': u'Hello',
u'state': u'US',
u'user': {u'login': u'JON', u'id': 33}},
{u'body': u'Hola',
u'state': u'ES',
u'user': {u'login': u'PABLO', u'id': 46}}
]
我想通過從'user'鍵中提取字典來獲得一個新列表並得到以下結果:
final_list = [
{u'body': u'Hello', u'state': u'US', u'login': u'JON', u'id': 33},
{u'body': u'Hola', u'state': u'ES',u'login': u'PABLO', u'id': 46}
]
我已經測試過這段代碼而沒有成功:
content = start_list[0]['user']
for element in start_list:
final_list.append({key: elemento[key] for key in
["body","state",contenuto]})
是否可以在python中執行for循環來執行此操作?
如果您有靜態dict架構,則可以執行以下操作:
final_list = [{
'body': d['body'],
'state': d['state'],
'login': d['user']['login'],
'id': d['user']['id'],
} for d in start_list]
如果您的dict架構是大/動態的,您可以這樣做:
final_list = []
for d in start_list:
r = {}
for key in d['user']:
r[key] = d['user'][key]
for key in d:
if key != 'user':
r[key] = d[key]
final_list.append(r)
如果要修改start_list
(就地執行),可以執行以下操作:
for d in start_list:
d.update(d['user'])
d.pop('user')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.