如何获取列表中字典的索引

时间:2015-03-28 15:36:20

标签: python list dictionary

test = [{"first" : "xyz", 'score': [1,2,3,4]},{"first" : "tests", 'score': [22,33,4]}]

我试图在测试中找到xyz并列出xyz的分数。

4 个答案:

答案 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'}]