我的代码应该使用称为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()
答案 0 :(得分: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']
答案 1 :(得分:0)
只需遍历它:
for x in dict.keys():
print(f'{x}: {dict[x]}')