python:读取json和循环字典 [英] python: read json and loop dictionary

查看:531
本文介绍了python:读取json和循环字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习python,我循环像这样json转换为字典:它的工作,但这是正确的方法吗?谢谢:)

  import json 

output_file = open('output.json' ()
output_json = json.loads(output_file)

在output_json中为
打印i
在output_json [i]中的k:
打印k,output_json [i] [k]

print output_json ['webm'] ['audio']
print output_json ['h264'] ['video']
print output_json ['ogg']

这里的JSON:



pre> {
webm:{
video:libvp8,
audio:libvorbis

h264:{
video:libx264,
audio:libfaac
},
ogg b $ bvideo:libtheora,
audio:libvorbis
}
}

这里输出:

 > h264 
音频libfaac视频libx264
ogg
>音频libvorbis视频libtheora webm
>音频libvorbis视频libvp8 libvorbis
> libx264 {u'audio':u'libvorbis',
> u'video':u'libtheora'}


解决方案

似乎一般很好。



没有必要先读取文件,然后使用加载。您可以直接使用负载。

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

使用i和k不正确。它们通常仅用于整数循环计数器。在这种情况下,它们是钥匙,所以更合适的东西会更好。可能将 i 重命名为 container k as ?传达更多信息的东西将更容易阅读和维护。



您可以使用 output_json.iteritems()在同一时间重复键和值两者。

 为majorkey,在output_json.iteritems()中扣除:
print majorkey
for subkey,value in subdict.iteritems():
print subkey,value


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 = open('output.json').read()
output_json = json.loads(output_file)

for i in output_json:
        print i
        for k in output_json[i]:
                print k, output_json[i][k]

print output_json['webm']['audio']
print output_json['h264']['video']
print output_json['ogg']

here the JSON:

{   
 "webm":{
    "video": "libvp8",
    "audio": "libvorbis"   
 },   
  "h264":   {
    "video": "libx264",
    "audio": "libfaac"   
 },   
  "ogg":   {
    "video": "libtheora",
    "audio": "libvorbis"   
 }
}

here output:

> h264 
audio libfaac video libx264 
ogg
> audio libvorbis video libtheora webm
> audio libvorbis video libvp8 libvorbis
> libx264 {u'audio': u'libvorbis',
> u'video': u'libtheora'}

解决方案

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

这篇关于python:读取json和循环字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆