Good evening, I have this kind of list:
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}}
]
I'd like to get a new list by extracting the dictionary from the 'user' key and get this result:
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}
]
I have already tested this code without success:
content = start_list[0]['user']
for element in start_list:
final_list.append({key: elemento[key] for key in
["body","state",contenuto]})
is it possible to do a for loop in python to do this?
If you have a static dict schema, you can do this:
final_list = [{
'body': d['body'],
'state': d['state'],
'login': d['user']['login'],
'id': d['user']['id'],
} for d in start_list]
If your dict schema is big/dynamic, you can do this:
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)
If you want to modify start_list
(do it in-place), you can do this:
for d in start_list:
d.update(d['user'])
d.pop('user')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.