Skip to content
Advertisement

KeyError: ‘variant’ while getting data from API , even tho variant data exists on API

[Here is the API snippet. I am working on]

1

Here is the code snippet that fetching API snippet above.

for i in parse_json["lines"]:
    list = []
    if (i["chaosValue"] > chaos_ex_ratio):
            value = (i["variant"],i["baseType"], i["exaltedValue"], "Exalted Orb", i["levelRequired"])
    else:
            value = (i["variant"],i["baseType"], i["exaltedValue"], "Chaos Orb", i["levelRequired"])
        list.append(value)

If I remove i[“variant”] everything works perfectly but i[“variant”] is throwing key error even tho “variant”: “Shaper/Redeemer” exists on the JSON file. Thanks for any help.

Error code:

Traceback (most recent call last):
  File "C:UsersemoscPycharmProjectsGithubPushspsychescape_price_fetcherpsychescape_price_fetchermain.py", line 265, in <module>
    BaseType_Values()
  File "C:UsersemoscPycharmProjectsGithubPushspsychescape_price_fetcherpsychescape_price_fetchermain.py", line 219, in BaseType_Values
    value = (i["variant"],i["baseType"], i["exaltedValue"], "Exalted Orb", i["levelRequired"])
KeyError: 'variant'

Advertisement

Answer

You’re showing us a screenshot where the first line has a variant, but your code will fail unless every line has a variant.

What is the output of this snippet?

for l in parse_json["lines"]:
    if "variant" not in l:
        print("Line {} does not have a 'variant'".format(l))

If it outputs any lines, there’s your problem. If it doesn’t, something deeper is going on. I would try to catch the KeyError exception and put a breakpoint in the handler to continue investigating.

Advertisement