python - 如何显示从字典中获得的键和更新值?
问题描述
我的代码应该删除字典中长度为 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'”
解决方案
你的问题可以用单线解决:
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()))
推荐阅读
- javascript - 获取最新的副本并将其通过电子邮件发送给自己
- f# - 'let' 之后的块未完成 - try/with
- java - 访问 RESTful Web 服务的问题
- google-bigquery - 在 bigquery 中删除和创建表是否会更新每天的配额限制?
- c# - 无法使用 NAudio 和 teVirtualMIDI 发送 MIDI 音符
- python - 例外:使用 InceptionV3 时,URL 获取失败...
- java - JNativeHook 库的 Java nativeKeyTyped 方法未在 Windows 10 上触发
- redis - Redis 中深度嵌套的数据结构
- node.js - 执行“npm start”时“找不到模块”[我应该如何处理我的错误?]
- javascript - 使用不同大小的图像调整滑块大小