【发布时间】:2021-06-11 12:05:17
【问题描述】:
如果键的值为“N/A”、“-”或“”,我正在尝试通过删除键来清理 json 对象,并且同样从任何列表中删除这些值中的任何一个。清洗对象示例:
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 是一个字典时,我进行集合比较的方式并不像我认为的那样工作。谁能赐教?
【问题讨论】:
标签: python json dictionary typeerror