Indexing a value in a nested dictionary

471 views python
5

I have a dictionary from an API request that looks somewhat like this:

{
"key 1": "value 1",
"key 2": "value 2",
"key 3": 
    {
        "key 4": "value 4",
        "key 5": "value 5",
        "key 6": "value 6"
    },
... # Additional fields here
}

And I need to save some values to another dictionary like {"key 2": "value 2","key 5":"value 5"}. In an attempt to make the code look nice I want to save the indexes of the values I need to keep in a list like ["key 2", "key 3/key 5"].

However I can't easily index a dictionary with "key 3/key 5" and was wondering if there is a way to do that.

For example:

dict={"username":"user",
      "email":"user@domain.com",
      "properties":{
          "favorite color":"blue"
          "favorite food":"apples"
          }
      }
savevalues=["email","properties/favorite food"]

which would return

{"email":"user@domain.com","favorite food":"apples"}

answered question

You example dict seems to be formatted incorrectly, missing an end brace?

Could you post the expected output, is not clear from the text what you want.

1 Answer

10

Since you're talking about using a list anyway, you could use nested lists/tuples to refer to indices in dictionaries within a dictionary.

d = {
"key 1": "value 1",
"key 2": "value 2",
"key 3": 
    {
        "key 4": "value 4",
        "key 5": "value 5",
        "key 6": "value 6"
    }
}

key_sets = (("key 2",), ("key 3", "key 5"))

for key_set in key_sets:
    value = d
    for key in key_set:
        value = value[key]
    print(value)
    # value 2
    # value 5

This assumes your key sets are always valid. If that's not an assumption you can make, you'll need to do some exception handling.

It could also probably be done more elegantly with some functional programming, but I don't think getting into that would be helpful here.

posted this

Have an answer?

JD

Please login first before posting an answer.