[英]Put key values in a list of Python dictionary
I have a python dictionary that looks something like this:我有一个看起来像这样的 python 字典:
{
"hits": [
{
"_source": {
"network": "att",
"month": january,
"volume": "30",
"mass": 3,
}
},
{
"_source": {
"network": "vzn",
"month": june,
"volume": "10",
"mass": 2,
}
}
]
}
I'd like to take this dictionary and put some things in lists.我想拿这本字典,把一些东西列在清单里。 For example, I'd like to get all the element's mass and volume and put them in a list format like so:例如,我想获取所有元素的质量和体积,并将它们放在列表格式中,如下所示:
mass = [3,2]
volume = [30, 10]
I know I can create a loop and loop through each element of the json and add it to each list, but I was wondering if there was a built in or more elegant way of doing this.我知道我可以创建一个循环并遍历 json 的每个元素并将其添加到每个列表中,但我想知道是否有内置或更优雅的方法来执行此操作。
A list-comprehension option:列表理解选项:
mass_list = 'mass:', [i['_source']['mass'] for i in d['hits']]
volume_list = 'volume:', [i['_source']['volume'] for i in d['hits']]
output:输出:
print(mass_list) # mass: [3, 2]
print(volume_list) # volume: ['30', '10']
Here is the code:这是代码:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.