【问题标题】:python parse multiple keyspython解析多个键
【发布时间】:2019-10-11 23:16:38
【问题描述】:

我有一个 API 返回这样的响应。

data = [
  {'id': 'x27fujsjfsfjsjf', 'price': '89992',  'type': 'ONE'}, {'id': 'ujufajfjfwau', 'price': '7777',  'type': 'ONE'}, {'id': 'x27adarasda', 'price': '88882',  'type': 'TWO'}
] 

我想成对解析响应,例如 id 和 price。我使用python Websocket客户端实时获取数据。

我现在使用:

 for d in data: 
       print (d['id])

但我找不到同时解析 id、price 和 type 的解决方案。因为我对特定 ID 的价格感兴趣。

【问题讨论】:

  • 您是否在每个对象中漏掉了一个逗号,还是这样?
  • 不,现在已修复。谢谢
  • 谢谢,您只是想同时打印 id、价格和类型?
  • 是的,没错。我不知道这对我来说怎么这么难:( 看起来很容易。

标签: json dictionary parsing


【解决方案1】:

你可以这样做。

for d in data:
    print (d['id'], d['price'], d['type'])

如果您想在某处使用这些值,您可以以相同的方式将这些值传递给另一个函数。

SO 中提供了更多信息

【讨论】:

    【解决方案2】:

    您只需“说出”您想从字典中打印的内容:

    data = [
            {'id': 'x27fujsjfsfjsjf', 'price': '89992', 'type': 'ONE'},
            {'id': 'ujufajfjfwau', 'price': '7777',  'type': 'ONE'},
            {'id': 'x27adarasda', 'price': '88882',  'type': 'TWO'}
    ]
    
    for item in data:
        print(item['id']) # this prints out the value of the ID
        print(item['price']) # this prints out the value of the PRICE
        print(item['type']) # this prints out the value of the TYPE
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-31
      相关资源
      最近更新 更多