简体   繁体   中英

python dict: nested dictionaries

I want to update keys from a JSON file (which is then converted to python dictionary). I would like to have a nested dictionary within my updated files but I don't know how to do this.

f = dict(
    source=result['sourcefile'], 
    destination=result['destinationfile']
)

In this code, I have result which is my JSON output. I have the keys sourcefile and destinationfile are the keys I get from the API. I would like to change them to source and destination . This code does the job until here; however, I would like my dictionary to be nested (whether with a list or another dict ). Something like below:

{"F":{"source":"samplevalue","destination":"samplevalue"}}

Here is sample code that incorporates the code you showed and produces the JSON you show. It simply makes the object as described and encodes it as JSON.

import json

result = {'sourcefile': "samplevalue", 'destinationfile':"samplevalue"}

f = dict(
                 source=result['sourcefile'],
                         destination=result['destinationfile']
                                         )
g = {"F": f}

print( json.dumps(g) )

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