我已经尝试了,您想使用
val not in inverse它,但是如果“列表在字典中”,则无法检查它。(
val是列表)
对于您的代码,简单的更改就可以满足您的要求:
def invert_dict(d): inverse = dict() for key in d: # Go through the list that is saved in the dict: for item in d[key]: # Check if in the inverted dict the key exists if item not in inverse: # If not create a new list inverse[item] = [key] else: inverse[item].append(key) return inverse



