简体   繁体   中英

Python dictionary operations

How can I remove the data key from this dictionary and convert it to this using a python function recursively?

request = {"data":{"a":[{"data": {"b": {"data": {"c": "d"}}}}]}}

response = {"a": [{"b":{"c": "d"}}]}

Yes, you can do this recursively, if all you have is lists and dictionaries, then that is pretty trivial. Test for the object type, and for containers, recurse:

def unwrap_data(obj):
    if isinstance(obj, dict):
        if 'data' in obj:
            obj = obj['data']
        return {key: unwrap_data(value) for key, value in obj.items()}

    if isinstance(obj, list):
        return [unwrap_data(value) for value in obj]

    return obj

Personally, I like using the @functools.singledispatch() decorator to create per-type functions to do the same work:

from functools import singledispatch

@singledispatch
def unwrap_data(obj):
    return obj

@unwrap_data.register(dict)
def _handle_dict(obj):
    if 'data' in obj:
        obj = obj['data']
    return {key: unwrap_data(value) for key, value in obj.items()}

@unwrap_data.register(list)
def _handle_list(obj):
    return [unwrap_data(value) for value in obj]

This makes it a little easier to add additional types to handle later on.

Demo:

>>> request = {"data":{"a":[{"data": {"b": {"data": {"c": "d"}}}}]}}
>>> unwrap_data(request)
{'a': [{'b': {'c': 'd'}}]}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM