jumpman8947
jumpman8947

Reputation: 289

Retrieving key, value of json data python

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

Upvotes: 1

Views: 14384

Answers (3)

Raunak Agarwal
Raunak Agarwal

Reputation: 7238

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.

Upvotes: 3

Jared Goguen
Jared Goguen

Reputation: 9008

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().

Upvotes: 6

Agustín
Agustín

Reputation: 1569

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

Upvotes: 1

Related Questions