2016-04-13 43 views
0

我現在有一本字典,像這樣:將列表作爲值反轉字典的最佳方法?

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'] 

我相信這是我遇到的問題是我無法成功地從列表中去除外側括號。

+0

提示:雙括號裏面是另一個列表 – Izkata

+0

列表,請參閱我的更新後 – david

+0

我知道這是這個問題,但我不知道如何糾正它。 – david

回答

0

如果我用您的編輯,這可能工作

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) 
+0

如何在我的字典中添加一個值列表?目前,我似乎只能在列表中添加一個列表,或者每個單獨的元素。我似乎在這兩者之間跳過,而不是隻有一個列表。 – david

+0

我試過你的更新函數,並得到TypeError:列表索引必須是整數,而不是unicode – david

+0

好吧,我更新了你自己的編輯。 –

1

該錯誤只是說,因爲他們是可變的列表不能用作字典的關鍵。但是,元組是不可變的,因此可以用作關鍵字。

一個可能的解決辦法可能是:

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]) 
+0

我已更新我的帖子 – david

0

這是相同的反向功能,你有一個,但考慮到該字典包含其中僅使用第一個元素列表的列表帳戶。我認爲這些數據的格式不正確,因此也沒有使用雙括號,但是通過這種修改就可以實現。

>>> 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'} 
+1

儘管此代碼可能會回答問題,但提供有關爲什麼和/或如何回答問題的其他內容將顯着提高其長期價值。請[編輯]你的答案,添加一些解釋。 – CodeMouse92

相關問題