python-遍历JSON列表以匹配特定的键值对

时间:2019-01-30 00:35:00

标签: python

我想遍历JSON响应以匹配特定的键值对以将其和同一列表中的另一个值打印出来。

JSON看起来像

[
{
    "status": "ok",
    "slot": null,
    "name": "blah",
    "index": 0,
    "identify": "off",
    "details": null,
    "speed": null,
    "temperature": null
},
{
    "status": "ok",
    "slot": null,
    "name": "blah1",
    "index": 0,
    "identify": "off",
    "details": null,
    "speed": null,
    "temperature": null
},
{
    "status": "ok",
    "slot": null,
    "name": "blah2",
    "index": 1,
    "identify": "off",
    "details": null,
    "speed": null,
    "temperature": null
}
]

到目前为止我尝试过的代码:

 url = http://something
 data = json.loads(r.get(url, headers=headers, verify=False).content.decode('UTF-8'))

 for value in data:
   if value['name'] == 'blah' or 'blah1':
        print(value)

我尝试了下一代:

match = next(d for d in data if d['name'] == 'blah')
yield next(match)

但是这些都不起作用。

我想要的输出是:如果是'name'='blah''name'='blah1',则要打印出名称和相关的状态

'name'='blah' 'status'='ok'

'name'='blah1' 'status'='ok'

我该如何使用Python?

3 个答案:

答案 0 :(得分:2)

我尝试了以下方法,并且有效:

for value in data:
   if value['name'] == 'blah' or value['name'] == 'blah1':
      print(value)

答案 1 :(得分:1)

您已经将next的值用于next。我会用这样的东西:

data = [
{
    "status": "ok",
    "slot": None,
    "name": "blah",
    "index": 0,
    "identify": "off",
    "details": None,
    "speed": None,
    "temperature": None
},
{
    "status": "ok",
    "slot": None,
    "name": "blah1",
    "index": 0,
    "identify": "off",
    "details": None,
    "speed": None,
    "temperature": None
},
{
    "status": "ok",
    "slot": None,
    "name": "blah2",
    "index": 1,
    "identify": "off",
    "details": None,
    "speed": None,
    "temperature": None
}
]

#This is the part you're trying to work
def get_name(data, name):
  return next(d for d in data if d.get('name', None) == name)

v = get_name(data, "blah")
if v:
  print(f"Name: {v['name']}, Status: {v['status']}")
else:
  print("No Value")

此打印:

"Name: blah, Status: ok"

答案 2 :(得分:1)

对于每个'name'值,检查其是否为in有效值:

for value in data:
    if value['name'] in ['blah', 'blah1']:
        print(value['name'], value['status'])

输出:

u'blah', u'ok'
u'blah1', u'ok'

更新评论中的问题: 要为变量名称动态分配值,最有效的方法是使用字典将每个变量名称分配为字典的keys和相应的values(取自答案{{3 }}):

import string

var = string.ascii_lowercase

d = {}
k = 0

for value in data:
    d[var[k]] = value['name']
    k += 1
    d[var[k]] = value['status']
    k += 1

现在我们有了一个变量名字典作为键,我们可以获取它们的赋值:

print(d['a']) # blah