简体   繁体   中英

How to create new json object from a dict in python?

What is the best way to create a dict, with some attributes, from another dict, in Python?

For example, suppose I have the following dict:

dict1 = { "name": "Juan", "lastname": "Gonzalez", "swimming": "yes", "soccer": "no"}

I would like to obtain:

dict2 = { "name": "Juan", "lastname": "Gonzalez", "hobbies": {"swimming": "yes", "soccer": "no"}}

Which I only need to add the "hobbies"

The easy answer:

dict2 = {"name": dict1["name"], "lastname": dict1["lastname"], hobbies: {"swimming": dict1["swimming"], "soccer": dict1["socccer"]}}

A more flexible answer:

toplevel_keys = ['name', 'lastname']
hobbies_keys = ['swimming', 'soccer']
dict2 = {key: dict1[key] for key in toplevel_keys}
dict2['hobbies'] = {key: dict1[key] for key in hobbies_keys}

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