将键值放在Python字典列表中

时间:2019-03-04 19:59:37

标签: python pandas

我有一个看起来像这样的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的每个元素,并将其添加到每个列表中,但是我想知道是否存在内置的或更优雅的方法。

2 个答案:

答案 0 :(得分:1)

列表理解选项:

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']

答案 1 :(得分:0)

代码如下:

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)