【问题标题】:Python: How do I print out values with their corresponding keys and sort them?Python:如何打印出带有相应键的值并对其进行排序?
【发布时间】:2019-05-23 01:27:19
【问题描述】:

我的代码应该使用名为 remove_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()

【问题讨论】:

    标签: python list dictionary for-loop key


    【解决方案1】:

    您可以使用字典和列表推导来实现此目的

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

    【讨论】:

      【解决方案2】:

      只需遍历它:

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

      【讨论】:

        猜你喜欢
        • 2022-06-11
        • 1970-01-01
        • 2014-06-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-08-22
        • 2021-07-03
        • 1970-01-01
        相关资源
        最近更新 更多