-1

I have a dict with a key slug and I want to put all key/value pairs in the dict into a child dict with the name taken from the slug.

For example, given this input:

{
    "tasks": {},
    "task_defaults": {
        "retry": {
            "count": 3,
            "delay": 2
        }
    },
    "slug": "test"
}

I want this output:

{
    "test": {
        "tasks": {},
        "task_defaults": {
            "retry": {
                "count": 3,
                "delay": 2
            }
        }
    }
}

How can I achieve this?

Daniel Pryden
  • 59,486
  • 16
  • 97
  • 135
copser
  • 2,523
  • 5
  • 38
  • 73
  • Possible duplicate of: https://stackoverflow.com/questions/3232943/update-value-of-a-nested-dictionary-of-varying-depth – Stanislav Ivanov Feb 01 '19 at 14:24
  • 2
    `'tasks'` key has an empty dictionary as its value in the input dictionary but in output dictionary, it's not the case. Is that a mistake or expected? – Austin Feb 01 '19 at 14:26
  • Please fix your indentation. – Kijewski Feb 01 '19 at 14:30
  • 1
    Do not delete your question when you get your answer. See https://meta.stackoverflow.com/questions/378440/caveat-emptor-making-students-aware-they-cannot-delete-their-homework-questions. –  Feb 01 '19 at 14:51
  • ok, sorry about that – copser Feb 01 '19 at 14:52

1 Answers1

2

If you're OK with returning a new dict object that references the inner values from the input dictionary, you can do this:

def group_by_slug(data):
    return {
        data['slug']: {
            key: value for key, value in data.items()
            if key != 'slug'
        }
    }
Daniel Pryden
  • 59,486
  • 16
  • 97
  • 135