Python 从JSON检索多个值
我定义了从JSON字符串中检索所需值的函数 第2部分问题:Python 从JSON检索多个值,python,json,Python,Json,我定义了从JSON字符串中检索所需值的函数 第2部分问题: def galPrice(commodity): comPrice = [item['meanPrice'] for item in data['lastStarport']['commodities'] if item['name'] == commodity] print json.dumps(comPrice) 问题1: 从上述函数返回的值为我提供了[378]如何返回项目名称和值,即[meanPrice:
def galPrice(commodity):
comPrice = [item['meanPrice'] for item in data['lastStarport']['commodities']
if item['name'] == commodity]
print json.dumps(comPrice)
问题1:
从上述函数返回的值为我提供了[378]
如何返回项目名称和值,即[meanPrice:378]
问题2:
在此示例中,我尝试打印多个选定的值,例如meanPrice
、buyPrice
和sellPrice
因此,输出将给我:
[meanPrice : 378],
[buyPrice : 224],
[sellPrice : 209]
我唯一能弄明白的方法是做以下几件事,我不确定这是不是最有效的方法
def galPrice(commodity):
meanPrice = [item['meanPrice'] for item in data['lastStarport']['commodities']
if item['name'] == commodity]
buyPrice = [item['buyPrice'] for item in data['lastStarport']['commodities']
if item['name'] == commodity]
sellPrice = [item['sellPrice'] for item in data['lastStarport']['commodities']
if item['name'] == commodity]
print 'Mean Price:', meanPrice
print 'Buy Price:', buyPrice
print 'Sell Price:', sellPrice
JSON:
您也可以使用helper函数
def get_commodity_data(commodity):
for item in data['lastStarport']['commodities']:
if item['name'] == commodity:
return item
return None
def galPrice(commodity):
comdata = get_commodity_data(commodity)
return {
'meanPrice': comdata['meanPrice'],
'buyPrice': comdata['buyPrice'],
'sellPrice': comdata['sellPrice'],
}
print galPrice('Explosives')
输出
{'sellPrice': 209, 'meanPrice': 378, 'buyPrice': 224}
我认为这个代码应该回答1)和2)。如果没有,请在下面发表评论,我将予以澄清
如果您不想硬编码所需的值,那么下面的代码更灵活
def galPrice(commodity, values):
comdata = get_commodity_data(commodity)
return dict(zip(values, [comdata[value] for value in values]))
print galPrice('Explosives', ['meanPrice', 'buyPrice', 'sellPrice'])
它提供与上述相同的输出
如果有多个商品名称相同,下面将列出每种商品的数据列表
def galPrice(commodity, values):
comdata = filter(lambda i: i['name'] == commodity,
data['lastStarport']['commodities'])
return [dict(zip(values, [com[value] for value in values]))
for com in comdata]
注意:这不再需要helper函数。它利用了内置函数和
首先,列表被过滤到只有那些具有所需名称的项目。然后从所述项目中提取所需的值
示例输出:
[{'sellPrice': 209, 'meanPrice': 378, 'buyPrice': 224},
{'sellPrice': 210, 'meanPrice': 378, 'buyPrice': 224}]
或者,如果您对列表理解语法非常熟悉:
def galPrice(commodity, values):
return [dict(zip(values, [com[value] for value in values if com['name'] == commodity]))
for com in data['lastStarport']['commodities']]
与上面相同的输出。谢谢,这是我希望实现的目标,因此,
meanPrice
的项目名称似乎将手动输入。感谢您的快速响应。@如果您不想硬编码输出所需的值,请参阅我的更新,以获得更灵活的解决方案。谢谢。这也会非常方便。在我的JSON的另一部分中,我有多个相同名称但不同子值的值。它只返回第一个条目,这是否正确,不确定我是否读错了,但我认为for item
语句将返回所有值?@Marct我更新了两种方法来做你想做的事情(最后)。第二种方法与您的原始代码非常相似-我意识到我误解了它的原始功能,抱歉。
def galPrice(commodity, values):
return [dict(zip(values, [com[value] for value in values if com['name'] == commodity]))
for com in data['lastStarport']['commodities']]