首页 > 解决方案 > 如何显示从字典中获得的键和更新值?

问题描述

我的代码应该删除字典中长度为 7 个或更少字符的同义词,一旦完成所有删除,我将需要按键顺序显示它。但是,我不知道如何将密钥和更新的值放在一起。预期的输出应该是这样的:

(按字母顺序排序键):

dangerous : ['hazardous', 'perilous', 'uncertain'] 
show : ['communicate', 'manifest', 'disclose']
slow : ['leisurely', 'unhurried']
word_dict = {'show': ['display', 'exhibit', 'convey', 'communicate', 'manifest', 'disclose'],
             'slow': ['unhurried', 'gradual', 'leisurely', 'late', 'behind', 'tedious', 'slack'],
             'dangerous': ['perilous', 'hazardous', 'uncertain']}

def main():
    edited_synonyms = remove_word(word_dict)
    key_order(edited_synonyms)

def remove_word(word_dict):
    dictionary = {}

    synonyms_list = word_dict.values()
    new_list = []
    for i in synonyms_list:
        new_list.extend(i)

    for word in new_list:
        letter_length = len(word)
        if letter_length <= 7:
            new_list.pop(new_list.index(word))

    value = new_list 
    keys_only = word_dict.keys()
    key = keys_only
    dictionary[key] = value
    return dictionary


def key_order(word_dict):
    word_list = list(word_dict.keys())
    word_list.sort()
    for letter in word_list:
        value = word_list[letter]
        print(letter, ": ", value)

main()

到目前为止发生的错误是“TypeError: unhashable type: 'dict_keys'”

标签: pythonlistdictionaryfor-loopkey-pair

解决方案


你的问题可以用单线解决:

waka_dict = {key: [w for w in word_dict[key] if len(w) > 7] for key in word_dict}

它将返回所需的字典:

{'dangerous': ['perilous', 'hazardous', 'uncertain'],
 'show': ['communicate', 'manifest', 'disclose'],
 'slow': ['unhurried', 'leisurely']}

(它将保存原始列表顺序)


如果你想成为你的 dict 命令,你应该记住 Python dicts 是无序的。你应该使用collections.OrderedDict

from collections import OrderedDict

ordered_dict = OrderedDict(sorted(waka_dict.items()))

推荐阅读