翻译字典

时间:2017-10-03 04:51:38

标签: python python-3.x dictionary

我试图反转下面的字典,但我一直收到错误消息builtins.TypeError: unhashable type: 'list'

input_dict = {
   1: ['hi', 'there', 'fred'], 
   2: ['there', 'we', 'go'],
   3: ['fred', 'was', 'there']}

这是我尝试做的事情

def make_index(words_on_page):
    """Invert the dictionary"""

    inverted = {}
    for index, word in words_on_page.items():
        if word in inverted:
            inverted[word].append(index)
        else:
            inverted[word] = [index]

任何人都可以指出我犯了哪个错误吗?

1 个答案:

答案 0 :(得分:0)

你只需要迭代与键对应的单词,比如

//Create where clause
$this->db->select('kd_x')
         ->where('a','11921212')
         ->from('MT_master');
$where_clause = $this->db->get_compiled_select();

//Create main query
$this->db->select('*');
     ->from('your_table');
     ->where("`kd_x` IN ($where_clause)", NULL, FALSE);

<强>结果

input_dict = {
    1: ['hi', 'there', 'fred'],
    2: ['there', 'we', 'go'],
    3: ['fred', 'was', 'there']
}


def make_index(words_on_page):
    """Invert the dictionary"""
    inverted = {}
    for index, words in words_on_page.items():
        for word in words:
            if word in inverted:
                inverted[word].append(index)
            else:
                inverted[word] = [index]
    return inverted

print(make_index(input_dict))