0

I have a json file, data.json

{
    "Nitrogen": [
        0.0173,
        0,
        0,
        0,
        28.0135
    ],
    "Oxygen": [
        0.0283,
        0,
        0,
        0,
        31.9988
    ]
}

I read the data like this:

import json

def read_data(path):
    with open(path, 'rU') as data:
        gasses = json.load(data)
        for gas in gasses:
            yield gas


if __name__ == '__main__':
    for row in read_data('data.json'):
        print(row)

It gives me

Nitrogen
Oxygen

How do I also get the value in the list instead?

2
  • 2
    for gas in gasses.items(): Commented Mar 16, 2015 at 16:03
  • also, you have a typo ,is yield not yeild Commented Mar 16, 2015 at 16:04

3 Answers 3

1

Like this:

gasses = json.load(data)
for gas, value in gasses.items():
    yield (gas, value)
Sign up to request clarification or add additional context in comments.

Comments

0

gas points to the key of your dictionary. gasses[gas] gives you the value.

Comments

0

Working Example — Tested with Python 2.6.9 and 2.7.10 and 3.2.5 and 3.4.3 and 3.5.0

import json


def read_data(path):
    with open(path, 'rU') as data:
        gasses = json.load(data)
        for gas, values in gasses.items():
            yield gas
            for value in values:
                yield value


if __name__ == '__main__':
    for row in read_data('data.json'):
        print(row)

Output

Nitrogen
0.0173
0
0
0
28.0135
Oxygen
0.0283
0
0
0
31.9988

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.