为什么递归清理json对象时会出现“unhable type:dict”错误?

2024-03-29 12:21:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图清除json对象,方法是删除值为“N/a”、““-”或“”的键,并从任何列表中删除这些值。要清理的对象的示例:

dirty = {
    'name': {'first': 'Robert', 'middle': '', 'last': 'Smith'},
    'age': 25,
    'DOB': '-',
    'hobbies': ['running', 'coding', '-'],
    'education': {'highschool': 'N/A', 'college': 'Yale'}
}

我发现了一个类似的问题,并修改了解决方案,提供了以下功能:

def clean_data(value):
    """
    Recursively remove all values of 'N/A', '-', and '' 
    from dictionaries and lists, and return
    the result as a new dictionary or list.
    """
    missing_indicators = set(['N/A', '-', ''])
    if isinstance(value, list):
        return [clean_data(x) for x in value if x not in missing_indicators]
    elif isinstance(value, dict):
        return {
            key: clean_data(val)
            for key, val in value.items()
            if val not in missing_indicators
        }
    else:
        return value

但我从字典理解中得到了不可破坏的类型:dict错误:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-79-d42b5f1acaff> in <module>
----> 1 clean_data(dirty)

<ipython-input-72-dde33dbf1804> in clean_data(value)
     11         return {
     12             key: clean_data(val)
---> 13             for key, val in value.items()
     14             if val not in missing_indicators
     15         }

<ipython-input-72-dde33dbf1804> in <dictcomp>(.0)
     12             key: clean_data(val)
     13             for key, val in value.items()
---> 14             if val not in missing_indicators
     15         }
     16     else:

TypeError: unhashable type: 'dict'

很明显,当val是一名教师时,我做集合比较的方式并不像我认为的那样有效。有人能给我一些启发吗


Tags: andkeyincleanfordatareturnif
3条回答

乍一看,这似乎是个问题:

if val not in missing_indicators

当您在set上使用in时,它将检查您询问的值是否在set项中。要成为Python中dict的键或set的成员,您使用的值必须是可哈希。您可以通过对Python中的值运行hash来检查该值是否可哈希:

>>> hash(1)
1
>>> hash("hello")
7917781502247088526
>>> hash({"1":"2"})
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'dict'

在您的代码片段中,看起来val是一个dict,您询问Python这个val是否是^{中存在的值之一。作为响应,Python尝试hash{},但失败了

您必须克服的障碍是,您的外部dict中的一些值本身就是dict,而其他值看起来像liststrint。在每种情况下,您需要不同的策略:检查val是什么类型的东西,然后相应地采取行动

相关问题 更多 >