test = [{"first" : "xyz", 'score': [1,2,3,4]},{"first" : "tests", 'score': [22,33,4]}]
我试图在测试中找到xyz
并列出xyz
的分数。
答案 0 :(得分:3)
您可以在next函数中使用生成器表达式:
>>> next(d['score'] for d in test if test and d['first']=='xyz')
[1, 2, 3, 4]
但由于字典中可能没有一个键,您可以使用try-except
表达式来处理错误:
>>> try :
... next(d['score'] for d in test if test and d['first']=='xyz')
... except KeyError:
... #proper error message
答案 1 :(得分:2)
字典的索引不是唯一的,因为字典是经过哈希处理的。您需要使用键访问字典中的值。一个小的解决方法可以是:
>>> test = [{"first" : "xyz", 'score': [1,2,3,4]},{"first" : "tests", 'score': [22,33,4]}]
>>> for i in test: # Iterate through the loop
... if i["first"] == 'xyz': # Check if the dict's value at "first"
... print("The score is {}".format(i["score"]))
... # Print the score
...
[1, 2, 3, 4]
答案 2 :(得分:0)
试试这个
>>>[{i:j} for i,j in enumerate(test) if "xyz" in j.values()]
[{0: {'first': 'xyz', 'score': [1, 2, 3, 4]}}]
返回键作为索引和值
OR
>>>[{i:j['score']} for i,j in enumerate(test) if "xyz" in j.values()]
[{0: [1, 2, 3, 4]}]
将key
作为index
返回,将值作为得分列表
编辑问题后更新
>>>[i['score'] for i in test if "xyz" in i.values()][0]
[1, 2, 3, 4]
避免例外情况,如果没有返回任何项目
it = iter([i['score'] for i in test if "xyz" in i.values()])
>>>next(it, None)
[1, 2, 3, 4]
>>>next(it, None)
None
答案 3 :(得分:0)
您可以使用filter
和lambda:
>>> filter(lambda d: 'first' in d and d['first']=='xyz', test)
[{'score': [1, 2, 3, 4], 'first': 'xyz'}]