0

Let's say I have this dictionary:

{
  "id": "132-sd-sa-23-a-1",
  "data": {
    "lastUpdated": { "S": "2020-07-22T21:39:20Z" },
    "profile": {
      "M": {
        "address": { "L": [] },
        "fakeField": { "S": "someValue" },
        "someKey": { "M": { "firstName": { "S": "Test" } } }
      }
    },
    "groups": {
      "L": [{ "S": "hello world!" }]
    }
  }
}

How can I remove the "M", "S", "L", etc. keys from the dictionary but keep the values. So it would turn into this:

{
  "id": "132-sd-sa-23-a-1",
  "data": {
    "lastUpdated": "2020-07-22T21:39:20Z",
    "profile": {
      "address": [],
      "fakeField": "someValue",
      "someKey": { "firstName": "Test" }
    },
    "groups": ["hello world!"]
  }
}

I could turn the dictionary into a string, loop through it, and remove what's necessary but that doesn't seem efficient or fast. I can't save the original list as the output that I'm hoping for initially so I need to convert it myself.

3
  • 2
    d['data']['profile'] = d['data']['profile']['M']? And so on. Commented Sep 16, 2020 at 20:23
  • 2
    Don't delete stuff, just make a new dictionary with the flattened keys/values. Commented Sep 16, 2020 at 20:24
  • Thanks! This showed me other ways to do it and how it might not be a good idea to modify the original list. Commented Sep 16, 2020 at 21:32

1 Answer 1

1

Sounds like a job for recursion:

def unsml(obj):
    if isinstance(obj, dict):
        if len(obj) == 1:
            (key, value), *_ = obj.items()  # get the only key and value
            if key in "SML":
                return unsml(value)
        return {
            key: unsml(value) if isinstance(value, dict) else value
            for key, value
            in obj.items()
        }
    elif isinstance(obj, list):
        return [unsml(value) for value in obj]
    return obj

Then just do new_dict = unsml(old_dict).

Sign up to request clarification or add additional context in comments.

4 Comments

"un-", as in remove, "sml" as in "S", "M", "L". Feel free to propose a better name.
you can use key, value = obj.popitem() to get the only key and value, otherwise great answer!
@Amir I could, yes, but then I'd change the original datastructure. I know the (key, value), *_ part is a bit obscure, but I like to keep functions pure, if possible.
Thank you so much! This is so much better than what I was doing (string manipulation).

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.