如何在Python中循环访问嵌套的json结构?

时间:2019-11-23 19:37:37

标签: python json

我无法在JSON中获取键值。

import json


packages = [
  [
    {
      "name": "a2ps",
      "installs": 61423
    },
    {
      "name": "aravis",
      "installs": 61424
    },
    {
      "name": "arangodb",
      "installs": 61425
    }
  ],
  [
    {
      "name": "argon2",
      "installs": 61420
    },
    {
      "name": "archivemount",
      "installs": 61421
    },
    {
      "name": "archivemail",
      "installs": 61422
    }
  ]
]

package_names = [package_name['name'] for package_name in packages]
package_installs = [package_installs['installs'] for package_installs in packages]

如您所见,我正在尝试获取软件包名称和安装号,但是在运行代码时出现错误。 这是完整的回溯:

Traceback (most recent call last):
  File "/Users/me/Documents/json.py", line 1, in <module>
    import json
  File "/Users/me/Documents/json.py", line 35, in <module>
    package_names = [package_name['name'] for package_name in packages]
  File "/Users/me/Documents/json.py", line 35, in <listcomp>
    package_names = [package_name['name'] for package_name in packages]
TypeError: list indices must be integers or slices, not str

但是,当我执行以下操作时,我会获取名称并进行安装,但仅适用于指定的软件包。


package_names = [package_name['name'] for package_name in packages[0]]
package_names2 = [package_name['name'] for package_name in packages[1]]
package_installs = [package_installs['installs'] for package_installs in packages[0]]
package_installs2 = [package_installs['installs'] for package_installs in packages[1]]
print(package_names, package_names2, package_installs, package_installs2)

输出:

['a2ps', 'aravis', 'arangodb'] ['argon2', 'archivemount', 'archivemail'] [61423, 61424, 61425] [61420, 61421, 61422]

5 个答案:

答案 0 :(得分:1)

您很接近,因为您有字典列表的列表,所以您需要在列表推导中使用两个循环:

 base = b(include_top=False, # include top refers if to include the dense layer that acts as the classifier, this is not needed in this case because we build one later
            weights="imagenet", # these are the weights used by the model that were learned from being trained on the imagenet dataset
            input_shape=(1000, 1000, 3)) # in case you work with rgb images, if you work with gray images you should use input_shape=(1000, 1000, 1)

x = base.output
predictions = layers.Dense(2, activation='softmax')(x)
model = Model(inputs=base.input, outputs=predictions)

model.compile(optimizer=optimizers.Adam(), 
          loss='categorical_crossentropy', 
          metrics=["categorical_accuracy"])


history = model.fit_generator(train,
                          steps_per_epoch=np.ceil(numImages/batchSize),
                          epochs=50,
                          verbose=2,
                          validation_data= val,
                          validation_steps=np.ceil(nunImages/size)
                          )
  

输出:

     
packages = [[{'name': 'a2ps', 'installs': 61423}, {'name': 'aravis', 'installs': 61424}, {'name': 'arangodb', 'installs': 61425}], [{'name': 'argon2', 'installs': 61420}, {'name': 'archivemount', 'installs': 61421}, {'name': 'archivemail', 'installs': 61422}]]

package_names = [package_name['name'] for ls in packages for package_name in ls]
package_installs = [package_install['installs'] for ls in packages for package_install in ls]

print(package_names)
print(package_installs)

如您所见,您也不需要使用['a2ps', 'aravis', 'arangodb', 'argon2', 'archivemount', 'archivemail'] [61423, 61424, >61425, 61420, 61421, 61422] 软件包,它们只是普通的普通Python jsonlist s。

答案 1 :(得分:1)

列表中列出了json的前两个最高级别,所以当您这样做时:

[package_name['name'] for package_name in packages]

您忘记了包中的每个元素都是另一个列表,而不是package_name字典。

请尝试使用双列表理解:

package_names = [package_name['name'] for sub_packages in packages for package_name in sub_packages]
package_installs = [package_install['installs'] for sub_packages in packages for package_install in sub_packages]

答案 2 :(得分:1)

   packages = [[{'name': 'a2ps', 'installs': 61423}, {'name': 'aravis', 'installs': 61424}, {'name': 'arangodb', 'installs': 61425}], [{'name': 'argon2', 'installs': 61420}, {'name': 'archivemount', 'installs': 61421}, {'name': 'archivemail', 'installs': 61422}]]

nameInstallDic= {package_name['name']: package_name['installs'] for ls in packages for package_name in ls}
name=nameInstallDic.keys()
installs=nameInstallDic.values()
name=list(name)
installs=list(installs)
print('name: ',name)
print('installs: ',installs)
  

outPut:   名称:['aravis','argon2','archivemail','a2ps','archivemount',   'arangodb']
  安装:[61424、61420、61422、61423、61421、61425]

     

,或者您可以使用下面的另一种方法

iterObj = iter(程序包)

package_names = [package_name['name'] for package_name in [*next(iterObj), *next(iterObj)]]

print('package_names :', package_names)

iterObj2 = iter(packages)
package_installs = [package_install['installs'] for package_install in [*next(iterObj2), *next(iterObj2)]]
print('package_installs:', package_installs)
  

输出:package_names:['a2ps','aravis','arangodb','argon2',   'archivemount','archivemail'] package_installs:[61423、61424、61425,   61420、61421、61422]

答案 3 :(得分:0)

您需要嵌套循环才能处理嵌套列表。

package_names = []
package_installs = []
for sublist in packages:
    for package in sublist:
        package_names.append(package['name'])
        package_installs.append(package['installs'])

答案 4 :(得分:0)

和其他人一样,您需要另一层:

package_names = [package_name['name'] for package in packages for package_name in package ]