Scott Scott - 2 months ago 7
JSON Question

print jsonfile key that it's value is selected by input

I have following codes and problems , Any idea would help. Thanks...

Nouns.json :

{
"hello":["hi","hello"],
"beautiful":["pretty","lovely","handsome","attractive","gorgeous","beautiful"],
"brave":["fearless","daring","valiant","valorous","brave"],
"big":["huge","large","big"]
}


Python file : this code would find word synonyms from json file and prints them

import random
import json

def allnouns(xinput):
data = json.load(open('Nouns.json'))
h = ''
items = []
T = False
for k in data.keys():
if k == xinput:
T = True
if T == True:
for item in data[xinput]:
items.append(item)
h = random.choice(items)
else:
for k in data.keys():
d = list(data.values())
ost = " ".join(' '.join(x) for x in d)
if xinput in ost:
j = ost.split()
for item in j:
if item == xinput :
h = k
break
else:
pass
else :
h = xinput

print(h)
xinput = input(' input : ')
allnouns(xinput)


Example:

example for input = one of keys :

>> xinput = 'hello' >> hello
>> 'hi' or 'hello' >> hi

example for input = one of values :

>> xinput = 'pretty' >> pretty
>> it should print it's key (beautiful) but it prints the first key (hello) >> hello


Problem is the last line of example

Any ideas how to fix it?

Answer

This looks massively over-complicated. Why not do something like:

import json

def allnouns(xinput):
    nouns = json.load(open('Nouns.json'))
    for key, synonyms in nouns.items():
        if xinput in synonyms:
            print(key)
            return;

xinput = input(' input : ')
allnouns(xinput)
Comments