0

I have a json file with a dictionary, and lists inside that dictionary

{"Dogs": [["spot"], 1], "Cats": [["whiskers"], 1], "fish": [["bubbles", "lefty", "tank", "goldie"], 4], "elephant": [["tiny", "spring"], 2], "zebra": [[], 1], "gazelle": [["red", "blue", "green", "yellow", "gold", "silver"], 6]}

There's more in the dictionary but from this example you can see the format.

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

This gives me a

too many values to unpack error.

I want the output to look like

dogs spot 1
cats whiskers 1
2
  • What do you want to happen for fish? You cant unpack into a list. Commented Jan 22, 2016 at 3:53
  • What should the output be when there are multiple things in the lists? Commented Jan 22, 2016 at 3:56

2 Answers 2

1

Presuming you want all animal names (?) output

...
for e, (v, z) in json_data.items():
    print('%s %s %d' % (e.lower(), ' '.join(v), z))

outputs

gazelle red blue green yellow gold silver 6
fish bubbles lefty tank goldie 4
cats whiskers 1
zebra  1
elephant tiny spring 2
dogs spot 1
Sign up to request clarification or add additional context in comments.

Comments

0

much simpler since the value is always going to be a list:

with open('myfile.json', 'r') as myfile:    
    json_data = json.load(t)
    for e, v in json_data.items():
        print e, " ".join(v[0]), v[1]

This gives:

gazelle red blue green yellow gold silver 6
fish bubbles lefty tank goldie 4
Cats whiskers 1
zebra  1
elephant tiny spring 2
Dogs spot 1

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.