[英]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?在 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}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.