python: read json and loop dictionary

后端 未结 2 1380
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-30 10:13

I\'m learning python and i loop like this the json converted to dictionary: it works but is this the correct method? Thank you :)

import json

output_file =          


        
2条回答
  •  一整个雨季
    2020-11-30 10:33

    That seems generally fine.

    There's no need to first read the file, then use loads. You can just use load directly.

    output_json = json.load(open('/tmp/output.json'))
    

    Using i and k isn't correct for this. They should generally be used only for an integer loop counter. In this case they're keys, so something more appropriate would be better. Perhaps rename i as container and k as stream? Something that communicate more information will be easier to read and maintain.

    You can use output_json.iteritems() to iterate over both the key and the value at the same time.

    for majorkey, subdict in output_json.iteritems():
        print majorkey
        for subkey, value in subdict.iteritems():
                print subkey, value
    

    Note that, when using Python 3, you will need to use items() instead of iteritems(), as it has been renamed.

提交回复
热议问题