2014-10-13 2 views
1

의 목록에서 딕셔너리에서 값을 얻을 수 있습니다 :어떻게 dicts dicts이 목록에서

lst = [{'fruit': 'apple', 'qty':'4', 'color': 'green'}, 
     {'fruit': 'orange', 'qty':'6', 'color': 'orange'}, 
     {'fruit': 'melon', 'qty':'2', 'color': 'yellow'}] 

내가 'color' 키의 값이 'yellow''fruit' 키의 값을 얻을 싶어요.

내가 시도 :

any(fruits['color'] == 'yellow' for fruits in lst) 

내 색상이 독특하고 True을 반환 때이 인스턴스에 'melon'이 될 것입니다 선택한 과일에 fruitChosen의 값을 설정합니다.

답변

2

당신은 발전기 표정으로 next() function을 사용할 수

fruit_chosen = next((fruit['fruit'] for fruit in lst if fruit['color'] == 'yellow'), None) 

이것은 과일 사전을 할당합니다 fruit_chosen, 또는 None에 맞게 일치가없는 경우. 기본값을 떠날 경우 일치하는 항목이없는 경우

또한, next()StopIteration을 올릴 것이다 :

try: 
    fruit_chosen = next(fruit['fruit'] for fruit in lst if fruit['color'] == 'yellow') 
except StopIteration: 
    # No matching fruit! 

데모 :

>>> lst = [{'fruit': 'apple', 'qty':'4', 'color': 'green'},{'fruit': 'orange', 'qty':'6', 'color': 'orange'},{'fruit': 'melon', 'qty':'2', 'color': 'yellow'}] 
>>> next((fruit['fruit'] for fruit in lst if fruit['color'] == 'yellow'), None) 
'melon' 
>>> next((fruit['fruit'] for fruit in lst if fruit['color'] == 'maroon'), None) is None 
True 
>>> next(fruit['fruit'] for fruit in lst if fruit['color'] == 'maroon') 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
StopIteration 
+0

'시도'블록에 표시 해 주셔서 감사합니다. – user94628

4

목록 이해를 사용하여 노란색 과일 목록을 얻을 수 있습니다.

lst = [{'fruit': 'apple', 'qty':'4', 'color': 'green'}, 
     {'fruit': 'orange', 'qty':'6', 'color': 'orange'}, 
     {'fruit': 'melon', 'qty':'2', 'color': 'yellow'}] 

>>> [i['fruit'] for i in lst if i['color'] == 'yellow'] 
['melon'] 
1

내가 filter이 상황에서 더 잘 맞는 것 같아요. 이것은 당신이 신속하고 효율적으로 예를 들어, 할당 할 수 있습니다

>>> lst = [{'fruit': 'apple', 'qty':'4', 'color': 'green'}, 
      {'fruit': 'orange', 'qty':'6', 'color': 'orange'}, 
      {'fruit': 'melon', 'qty':'2', 'color': 'yellow'}] 
>>> dct = {f['color']: f['fruit'] for f in lst} 
>>> dct 
{'orange': 'orange', 'green': 'apple', 'yellow': 'melon'} 

: 당신이 'color' 키를 고유 것이라고 확신 경우

result = [fruits['fruit'] for fruits in filter(lambda x: x['color'] == 'yellow', lst)] 
+0

그러면 목록이 생성됩니다. 나는'filter()'가 더 낫다는 것에 동의하지 않는다. 이미''fruit ''키를 추출하기 위해리스트 이해력을 사용해야 할 때가 아니다. –

+0

@MartijnPieters는 각자 고유합니다. 파이썬을 많이 사용할수록'map'과'filter' 함수의 팬이 늘어납니다. 아마 결국 다른쪽으로 돌아갈 것이지만 "나에게 색이 노란색 인 사람들이 필터링 한 모든 dict의 '과일'키 값을 말해줘. –

+1

'filter()'를 사용한다면'map from (itemgetter ('fruit'), filter (...))'연산자에서 import mapgetter를 사용하십시오. –

2

, 당신은 쉽게 사전 매핑 {color: fruit}을 구축 할 수 있습니다

fruitChosen = dct['yellow'] 
관련 문제