Python:如何打印出带有相应键的值并对它们进行排序?

2024-04-19 21:28:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我的代码应该在现有同义词词典的基础上创建另一个词典,使用名为remove\u word()的函数并将现有词典作为参数,删除同义词7个或更少的字符。它应该返回一个新字典,其中包含如下更新的值:

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

使用key_order()函数,我希望生成一个键列表,并使用sort()方法按字母顺序对键进行排序,然后循环遍历已排序的键并打印出相应的值。你知道吗

输出应如下所示,按字母顺序排序:

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.append(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()


Tags: keynewvalueshowkeysdictremovelist
2条回答

您可以使用字典和列表来实现这一点

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

new_word_dict = {k:[l for l in v if len(l) > 7] for k,v in word_dict.items()}
for key in sorted(new_word_dict.keys()):
    print(f"{key} : {new_word_dict[key]}")

输出

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

只需遍历它:

for x in dict.keys():
    print(f'{x}: {dict[x]}')

相关问题 更多 >