首页 > 解决方案 > Python 字典键/值抓取

问题描述

我目前是 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()

标签: pythonjson

解决方案


您应该检查该键是否存在于字典中,然后获取该键的值(尽管正如我看到的 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()

推荐阅读