2016-04-13 117 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

相关问题