Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/299.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将键值放入Python字典列表中_Python_Pandas - Fatal编程技术网

将键值放入Python字典列表中

将键值放入Python字典列表中,python,pandas,Python,Pandas,我有一本python字典,看起来像这样: { "hits": [ { "_source": { "network": "att", "month": january, "volume": "30", "mass": 3, } }, { "_source": { "network": "vzn",

我有一本python字典,看起来像这样:

{
    "hits": [
    {
       "_source": {
           "network": "att",
           "month": january,
           "volume": "30",
           "mass": 3,
       }
    },
    {
       "_source": {
           "network": "vzn",
           "month": june,
           "volume": "10",
           "mass": 2,
         }
     }
  ]
}
我想拿着这本词典,把一些东西列在单子上。例如,我想获得所有元素的质量和体积,并将它们放在如下列表格式中:

mass = [3,2]
volume = [30, 10]

我知道我可以通过json的每个元素创建一个循环,并将其添加到每个列表中,但我想知道是否有一种内置的或更优雅的方法来实现这一点。

列表理解选项:

mass_list = 'mass:', [i['_source']['mass'] for i in d['hits']]

volume_list = 'volume:', [i['_source']['volume'] for i in d['hits']]
输出:

print(mass_list)   # mass: [3, 2]
print(volume_list) # volume: ['30', '10']
代码如下:

a={
    "hits": [
    {
       "_source": {
           "network": "att",
           "month": 'january',
           "volume": "30",
           "mass": 3,
       }
    },
    {
       "_source": {
           "network": "vzn",
           "month": 'june',
           "volume": "10",
           "mass": 2,
         }
     }
  ]
}

a=a.items();

mass=[]
volume=[]

for value in a:
    for k in value[1]:
        k=list(k.items());
        volume.append(k[0][1]['volume'])
        mass.append(k[0][1]['mass'])

print(mass)
print(volume)

除了使用循环外,“内置或更优雅的方式”可能只是一个列表理解。这取决于你想要抓取多少键。您可能会考虑列表理解“更优雅”,但是如果您正在抓取10个键来制作10个列表,那么在“<代码> > 循环中,而不是10个列表通知书,就可能更快地单步传递数据,而没有预先构建的方法来解析您定制的数据结构。