简体   繁体   中英

How do I transform this dictionary in python?

I'm getting results from an external API as a dictionary in the format:

{data:[{values:[{'end_time':'2013-10-03T07:00:00+0000', value:{'mobile':4, 'search':3}}, {'end_time':'2013-10-04T07:00:00+0000', value:{'source':2}}]}]}

and I want to transform it into a dictionary with the format:

{'2013-10-03T07:00:00+0000':{'mobile':4, 'search':3},'2013-10-04T07:00:00+0000':{'source':2}}

When I try the following, I get the error SyntaxError: keyword can't be an expression for the line starting with output_dict :

def dict_cleaner(input_dict):
    for day in input_dict['data'][0]['values'][0]['end_time']:
        output_dict = dict(input_dict['data'][0]['values'][0]['end_time']=input_dict['data'][0]['values'][0]['value'])
    return output_dict

What am I doing wrong here?

@Kevin is right. If you're trying to create a dict why not just do

{input_dict['data'][0]['values'][0]['end_time']: input_dict['data'][0]['values'][0]['value']}

also, you can try comprehension instead of looping

output_dict = {d['end_time']: d['value'] for d in input_dict['data'][0]['values']}

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.

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