我現在有一本字典,像這樣:將列表作爲值反轉字典的最佳方法?
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