我现在有一本字典,像这样:将列表作为值反转字典的最佳方法?
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_dict [O] .append(q [0] [0]) 其中我假设将剥离外侧括号,而不是这个,它仅附加列表中的第一个值:
[u'app-1']
我相信这是我遇到的问题是我无法成功地从列表中去除外侧括号。
提示:双括号里面是另一个列表 – Izkata
列表,请参阅我的更新后 – david
我知道这是这个问题,但我不知道如何纠正它。 – david