2014-01-11 4 views
0

저는 파이썬에서 사전 목록을 가지고 있으며 특정 용어에 대한 사전 항목이 있는지 확인하려고합니다. 이 구문사전 값 가져 오기 Python

if any(d['acronym'] == 'lol' for d in loaded_data): 
     print "found" 

을 사용하여 작동하지만 나는 또한 내가 [ '약자'] [ '의미'] D 뜻이 키에 저장된 값을 얻을 싶어요. 내 문제는 파이썬이 그것을 인쇄하려고 할 때 d에 대해 알지 못한다는 것이다. 어떤 제안이라도, 어쩌면 모든 목록을 통해 다시 반복하지 않고 어떻게 발생 인덱스를 얻을 수 있습니까? 감사!

답변

2

acronym == lol을 포함한 사전 목록 :

l = filter(lambda d: d['acronym'] == 'lol', loaded_data) 
if l: 
    print "found" 
    print l[0] 

any 기능을 전혀 사용하지 않아도됩니다.

+0

완벽, 그게 내가 찾고 있던 바로 그거야 !! 많은 많은 감사합니다! :) – Crista23

+0

@ Crista23 나는 질문을 업데이트했기 때문에 기쁘다.'any'에 대한 필요성은 없다. –

+0

그러나 첫 번째로 일치하는 사전이 발견 된 후에도 루핑을 계속한다. – RemcoGerlich

0

당신은 그냥 거기에 있는지 확인하기보다는, 항목을 사용하려면 :

for d in loaded_data: 
    if d['acronym'] == 'lol': 
     print("found") 
     # use d 
     break # skip the rest of loaded_data 
+0

감사합니다. 나는이 물건을 피할 수있는 방법이 있기를 바랬습니다! :-) – Crista23

+0

'any' 체크는 아무렇지도 않게 숨 막힐 것입니다. 그래서 덜 효율적입니다! – jonrsharpe

0

any()는 다시 부울 당신을 제공합니다, 당신은 그것을 사용할 수 있습니다.

for d in loaded_data: 
    if d['acronym'] == 'lol': 
     print "found" 
     meaning = d['meaning'] 
     break 
else: 
    # The else: of a for runs only if the loop finished without break 
    print "not found" 
    meaning = None 

편집 : 그래서 그냥 루프를 작성하거나 약간 더 일반적인 기능으로 변경 :

filter(lambda d: d['acronym'] == 'lol', loaded_data) 

것은 반환됩니다 : 당신은 그냥 filter 기능을 사용할 수 있습니다

def first(iterable, condition): 
    # Return first element of iterable for which condition is True 
    for element in iterable: 
     if condition(element): 
      return element 
    return None 

found_d = first(loaded_data, lambda d: d['acronym'] == 'lol') 
if found_d: 
    print "found" 
    # Use found_d 
3

당신은 next을 사용할 수 있습니다 (당신이 첫 번째 신경 또는 대안 있음) 가장 한 경기에서 거기 알고있는 경우 : 다음

>>> loaded_data = [{"acronym": "AUP", "meaning": "Always Use Python"}, {"acronym": "GNDN", "meaning": "Goes Nowhere, Does Nothing"}] 
>>> next(d for d in loaded_data if d['acronym'] == 'AUP') 
{'acronym': 'AUP', 'meaning': 'Always Use Python'} 

그리고 당신이 같은 예외 또는 None을할지 여부에 따라 - 발견되지 값 : 당신이 원하는 경우

>>> next(d for d in loaded_data if d['acronym'] == 'AZZ') 
Traceback (most recent call last): 
    File "<ipython-input-18-27ec09ac3228>", line 1, in <module> 
    next(d for d in loaded_data if d['acronym'] == 'AZZ') 
StopIteration 

>>> next((d for d in loaded_data if d['acronym'] == 'AZZ'), None) 
>>> 

당신도 직접 값이 아닌 DICT를 얻을 수 :

>>> next((d['meaning'] for d in loaded_data if d['acronym'] == 'GNDN'), None) 
'Goes Nowhere, Does Nothing' 
+0

+1 전체 목록을 반복하지 않는 아주 좋은 방법입니다. –

0
firstone = next((d for d in loaded_data if d['acronym'] == 'lol'), None) 

은 조건이 적용되는 첫 번째 사전을 제공하고, 그러한 사전이없는 경우 None을 제공합니다.