1

I have a Json file with a dictionary that looks like

{"tvs": 92, "sofas": 31, "chairs": 27, "cpus": 007}

I'm trying loop though the dictionary and print the key with its corresponding value, in my code I'm getting a too many values to unpack error.

with open('myfile.json', "r") as myfile:
json_data = json.load(myfile)
for e, v in json_data:
  for key, value in e.iteritem():
    print key, value

3 Answers 3

6

So, by default a dict will iterate over its keys.

for key in json_data:
    print key
# tvs, sofas, etc...

Instead, it seems like you want to iterate over the key-value pairs. This can be done by calling .items() on the dictionary.

 for key, value in json_data.items():
    print key, value

Or you can iterate over just the values by calling .values().

Sign up to request clarification or add additional context in comments.

Comments

3

Try this:

with open('myfile.json', "r") as myfile:
    json_data = json.load(myfile)
    for e, v in json_data.items():
        print e,v

You have an extra loop in your code, also, the input file has invalid data 007. Loading it into json should give you an error.

Comments

1

Is this what you're looking for?

>>> json = {"tvs": 92, "sofas": 31, "chairs": 27, "cpus": 007}
>>> for j in json:
...     print j, json[j]
... 
chairs 27
sofas 31
cpus 7
tvs 92

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.