Py学习  »  Python

Python:转换深度嵌套字典或数组中的类型

David Ferris • 6 年前 • 1952 次点击  

我已经编写了以下helper函数来将objectid(bson类型)转换为字符串。该函数应适用于深度嵌套的字典、数组和二者的组合。

当前功能如下:

from datetime import datetime
from bson import ObjectId

def clean_dict_helper(d):
    if not d:
        return None
    if isinstance(d, list):  # For those db functions which return list
        if len(d) == 0:
            return []
        return [clean_dict_helper(x) for x in d]
    for k, v in d.items():
        if isinstance(v, dict):
            v = clean_dict_helper(v)
            d.update({k: v})
        else:
            if isinstance(v, ObjectId):
                v = str(v)
            elif isinstance(v, datetime):
                v = str(v)
            d.update({k: v})
    return d


test_case = {'id': bson.ObjectId("5e126ddf276ab18820e00ddf"), 'arr': [{'value': 4, 'id': bson.ObjectId("5e126ddf276ab18820e00ddf")}]}

result = clean_dict_helper(test_case)

print(result)
>>> {'arr': [{'id': ObjectId('5e126ddf276ab18820e00ddf'), 'value': 4}], 'id': '5e126ddf276ab18820e00ddf'}

然而,对于数组中的对象,它似乎失败了。我想知道是否有更好的方法来遍历嵌套的iterable并转换类型?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/52443
文章 [ 1 ]  |  最新文章 6 年前