我现在有一本这样的字典:
app_dict = {test1 : [[u'app-1', u'app-2', u'app-3', u'app-4']]}我有一个逆转字典的函数(事实证明它正在使用另一本字典)。
def reverse_dictionary(self, app_dict):
""" In order to search by value, reversing the dictionary """
return dict( (v,k) for k in app_dict for v in app_dict[k] )当我执行以下操作时,会出现错误:
data = reverse_dictionary(app_dict)
print data
ERROR:
return dict( (v,k) for k in app_dict for v in app_dict[k] )
TypeError: unhashable type: 'list'我不确定,但我认为问题在于我的字典是如何构造的,我不知道为什么我的列表中有两个括号,而且我似乎无法删除它们。如何修改reverse_dictionary函数以使用app_dict?
编辑:
new_dict = collections.defaultdict(list)
app_dict = collections.defaultdict(list)
#at this point, we have filled app_dict with data (cannot paste here)
for o, q in app_dict.items():
if q[0]:
new_dict[o].append(q[0])注意,当我此时打印new_dict时,我的字典值以如下格式显示(带有双括号):[U‘’app 1‘,u’‘app 2’,u‘’app 3‘,u’‘app 4’]
如果我将追加行更改为: new_dicto.append(q),它将去掉外部括号,而不是这样,它只会追加列表中的第一个值:
[u'app-1']我相信这就是我面临的问题,我不能成功地从名单上去掉外部的括号。
发布于 2016-04-13 18:16:44
如果我使用您的编辑,这可能会奏效。
new_dict = collections.defaultdict(list)
app_dict = collections.defaultdict(list)
#at this point, we have filled app_dict with data (cannot paste here)
for o, q in app_dict.items():
if q[0]:
for value in q[0]:
new_dict[o].append(value)发布于 2016-04-13 18:20:26
错误只是说列表不能作为字典中的键使用,因为它们是可变的。但是,元组是不可变的,因此可以用作键。
一项可能的工作是:
def reverse_dictionary(self, app_dict):
""" In order to search by value, reversing the dictionary """
return dict( (v,k) if type(v) != list else (tuple(v), k) for k in app_dict for v in app_dict[k])发布于 2016-04-13 18:38:41
这是与您所拥有的相同的反向函数,但是要考虑到字典包含一个列表列表,其中只使用第一个元素。我认为,数据的格式不正确,因此采用了两个括号,但经过这一修改,数据才能奏效。
>>> dict([(v, k) for k in app_dict for v in app_dict[k][0]])
{u'app-4': 'test1', u'app-3': 'test1', u'app-2': 'test1', u'app-1': 'test1'}https://stackoverflow.com/questions/36606355
复制相似问题