Python:如何打印出带有相应键的值并对其进行排序?
我的代码应该使用名为remove_word()的函数并将现有字典作为参数,在现有同义词字典的基础上创建另一个字典,删除同义词7个或更少的字符。它应该返回一个新字典,其中包含如下更新的值:Python:如何打印出带有相应键的值并对其进行排序?,python,list,dictionary,for-loop,key,Python,List,Dictionary,For Loop,Key,我的代码应该使用名为remove_word()的函数并将现有字典作为参数,在现有同义词字典的基础上创建另一个字典,删除同义词7个或更少的字符。它应该返回一个新字典,其中包含如下更新的值: {'slow' : ['leisurely', 'unhurried'], 'show' : ['communicate', 'manifest', 'disclose'], 'dangerous' : ['hazardous', 'perilous', 'uncertain']} 使用key_order()
{'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()
word_dict={'show':['display','exhibit','transfer','communicate','manifest','expose'],
‘慢’:[‘从容不迫’、‘循序渐进’、‘悠闲’、‘迟到’、‘落后’、‘乏味’、‘松弛’],
“危险的”:[“危险的”、“危险的”、“不确定的”]]
def main():
编辑的同义词=删除单词(单词)
键顺序(已编辑的同义词)
def删除单词(单词dict):
字典={}
同义词列表=单词目录值()
新列表=[]
对于同义词列表中的i:
新列表。附加(i)
对于新列表中的单词:
字母长度=len(单词)
如果字母_长度只需迭代:
for x in dict.keys():
print(f'{x}: {dict[x]}')
您可以使用字典和列表理解来实现这一点
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']