Python Dict键/值抓取



我目前是Python的新手。

我正在制作一个字典应用程序来学习。

然而,在我的一个函数中,我很难获得正确的输出。

我希望用户输入一个单词,并返回单词(键(和定义(值(。

我从中提取的JSON文件可以在这里找到:https://github.com/prestonjohnson17/Dictionary

import json
data = json.load(open("data.json"))
type(data)
def finding_def():                       
user_word = data[input(str())]       
if data.keys() == user_word:         
print(user_word)                 
else:                                
print ("not a real word")
finding_def()

您应该检查字典中是否存在该键,然后获取该键的值(尽管正如我在JSON文件中看到的那样,该值本身是一个数组;您应该处理打印数组的所有条目(。

def finding_def():                       
user_word = input()    
if user_word in data:
print("Entries:")
for entry in data[user_word]:     
print(entry)                 
else:                                
print("not a real word")
finding_def()

这是一个clever,但在这个过程中失去了一些可读性。

import json
data = json.load(open("data.json"))
print(data.get(input(), "not a real word"))

试试这个。

import json
data = json.load(open("data.json"))
def finding_def():                       
user_word = input("Enter word: ")
value = data.get(user_word, "not a real word")
print(value)
finding_def()

最新更新