0

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"

8
  • 1
    What does this have to do with JSON? The title is about JSON, but the question itself is about transforming the dictionary. Which one is it? Commented Apr 21, 2022 at 9:24
  • Please update your question with the code you have tried. Commented Apr 21, 2022 at 9:26
  • What can vary? Is the dictionary always in the form {"name": ..., 'lastname": ..., "swimming": ..., "soccer": ...} or do you want to extract all keys other than "name" and "lastname", or something else? Commented Apr 21, 2022 at 9:26
  • Do you want to put all keys in dict1 that are not 'name' or 'lastname' into hobbies? Commented Apr 21, 2022 at 9:28
  • @ForceBru You are right I would like to transform the dict1 to dict2.. Commented Apr 21, 2022 at 9:29

1 Answer 1

2

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}
Sign up to request clarification or add additional context in comments.

2 Comments

Hello again, what if the dict 2 hat different keys for some persons? what could you recommend me?
It depends on which keys are different. I can't really help you further without knowing more.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.