解析嵌套字典中的列表 Python

Parse List in nested dictionary Python

data = {
    "persons": {"1": {"name": "siddu"}, "2": {"name": "manju"}},
    "cars": {
        "model1": {
            "make": 1990,
            "company_details": {
                "name": "Ford Corporation",
                "country": "US",
                "some_list": [1, 2, 1],
            },
        },
        "model2": {
            "make": 1990,
            "company_details": {
                "name": "Ford Corporation",
                "country": "US",
                "some_list": [1, 2, 1, 1, 1],
            },
        },
    },
}

这是我的 python 对象,我如何识别 Key's-Value 是一个列表。这里的例子,在遍历'print(data["cars"]["model1"]["company_details"]["some_list"])'之后我得到了列表,因为它是一个小字典这很容易,但是如果我将来遇到 list 作为其他键的值,我怎么能识别相同的值。

示例:

data = {
    "persons": {"1": {"name": "siddu"}, "2": {"name": "manju"}},
    "cars": {
        "model1": {
            "make": 1990,
            "company_details": {
                "name": "Ford Corporation",
                "country": "US",
                "some_list": [1, 2, 1],
            },
        },
        "model2": {
            "make": 1990,
            "company_details": {
                "name": "Ford Corporation",
                <b>"country": ["US", "UK", "IND"],</b>
                "some_list": [1, 2, 1, 1, 1],
            },
        },
    },
}

任何人都可以 suggest/guide 我了解如何识别键的值是一个列表。 最终目标是删除列表中的重复项(如果存在)? 非常感谢:)

你可以有一个递归函数,它可以达到任何深度并使列表中的项目独一无二,如下所示:

In [8]: def removeDuplicatesFromList(di):
   ...:     for key, val in di.items():
   ...:         if isinstance(val, dict):
   ...:             removeDuplicatesFromList(val)
   ...:         elif isinstance(val, list):
   ...:             di[key] =list(set(val))
   ...:         else:
   ...:             continue
   ...:
   ...:
In [9]: removeDuplicatesFromList(data)

In [10]: data
Out[10]:
{'persons': {'1': {'name': 'siddu'}, '2': {'name': 'manju'}},
 'cars': {'model1': {'make': 1990,
   'company_details': {'name': 'Ford Corporation',
    'country': 'US',
    'some_list': [1, 2]}},
  'model2': {'make': 1990,
   'company_details': {'name': 'Ford Corporation',
    'country': 'US',
    'some_list': [1, 2]}}}}