题解 | #字典新增#

字典新增

https://www.nowcoder.com/practice/a69d651105ee4cfd86c56418f0aa9de3

#看了下其他人的解题,大都缺失了判断单词是否已存在的代码,补充一下
english_dict = {
    "a": ["apple", "abandon", "ant"],
    "b": ["banana", "bee", "become"],
    "c": ["cat", "come"],
    "d": "down",
}

new_key = input()
new_value = input()
words = [i for inner_words in english_dict.values() for i in inner_words]   #逐一取出所有单词

if new_key in english_dict.keys() and new_value not in words:               #判断单词是否已在原字典中
    english_dict[new_key].append(new_value)
elif new_key in english_dict.keys() and new_value in words:
    print('The word is already in your dictionary!')
else:
    english_dict[new_key] = new_value

print(english_dict)

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务