2014-06-24 1 views
2

여러 사전에서 키를 검색하는 가장 좋은 방법은 무엇입니까 여러나는 우리가이 같은 파이썬에서 키를 검색 할 수 있습니다 알고 파이썬

if key in (myDict_1.keys() + myDict_2.keys()): 
    #Do something here 

을 수행하여

if key in myDict_1: 
    #Do something here 
elif key in myDict_2: 
    #Do something here 

또는 ELIF 문을 사용하여 사전을하지만 시든하는 더 간결한 방법이 if-else를 사용하거나 명시 적으로 키 목록을 추가하지 않고 두 개의 서로 다른 dict에서 Python의 키를 찾으십니까?

+10

'어떤 (dicts에서 D를위한 D 키) 경우 : #은 something' –

+1

또는 두 dicts 당신은 간단 유지하고 dict2' –

+0

에 dict1 또는 키의 키 그럴 생각하면'할 수있는 작업을 수행. 'if, elif'를 사용해야하는데, 나중에 조건을 만족하는 dict 키를 모르기 때문에'myDict_1.keys() + myDict_2.keys()) '키를 입력하면 도움이되지 않습니다. –

답변

2

작성 귀하의 질문에 대한 답변은 다음과 같습니다

if any(key in d for d in dicts): 
    # do something 

당신이 키를 포함하는 사전 또는 사전에 알고 싶다면, 당신은 itertools.compress()를 사용할 수 있습니다

>>> d1 = dict(zip("kapow", "squee")) 
>>> d2 = dict(zip("bar", "foo")) 
>>> d3 = dict(zip("xyz", "abc")) 
>>> dicts = d1, d2, d3 

>>> from pprint import pprint 
>>> pprint(dicts) 
({'a': 'q', 'k': 's', 'o': 'e', 'p': 'u', 'w': 'e'}, 
{'a': 'o', 'b': 'f', 'r': 'o'}, 
{'x': 'a', 'y': 'b', 'z': 'c'}) 

>>> from itertools import compress 
>>> for d_with_key in compress(dicts, ("a" in d for d in dicts)): 
...  print(d_with_key) 
... 
{'a': 'q', 'p': 'u', 'k': 's', 'w': 'e', 'o': 'e'} 
{'a': 'o', 'r': 'o', 'b': 'f'} 
1

올바른 방법이 될 것이다 Zero가 작성한대로 :

아래의 주석을 읽으십시오 :

itertools.chain 기능을 사용하여 두 사전의 키를 포함하는 튜플을 만들 수도 있습니다.

>>> a = {1:2} 
>>> b = {3:4} 
>>> c = {5:6, 7:8} 
>>> print(tuple(itertools.chain(a, b, c))) 
(1, 3, 5, 7) 

그래서 당신도 할 수 있습니다

if x in tuple(itertools.chain(a, b, c)): 
    # Do something 
+0

'''print (list (zip (a, b, c)) [0])'''리스트를 생성해야합니까? – wnnmaw

+1

nop, 마지막에'[0]'을보고 닫는')' –

+0

오, 비웃음 직전을보세요. 이것은 3.x입니까? 2.7에'''list (zip ({5 : 'a'}, {6, 'b'})) [0]'''을 실행하면'''(5, 'b')''' – wnnmaw

0

왜 당신은 그 이상 목록과 간단한 루프와 같은 반복 가능한에서 dicts을 넣지 마십시오? 당신은 그렇게 함수로 표현할 수 있습니다.

def has_key(key, my_dicts): 
    for my_dict in my_dicts: 
     if key in my_dict: 
      return True 
    return False 

이렇게 사용됩니다.

>>> dict1 = {'a':1, 'b': 2} 
>>> dict2 = {'b':10, 'c': 11} 
>>> has_key('b', [dict1, dict2]) 
True 
1

약간의 목록을 이해할 수도 있습니다. 만약 당신이 단순히 키가 dicts의 컨테이너에 있는지 확인하려고한다면, any()은 정확히 그렇게합니다; 당신이 다시 DICT (또는 dicts)를 얻고 그들과 함께 작업 할 경우,이 같은 아마 뭔가 충분 :

>>> def get_dicts_with_key(some_key, *dicts): 
...  return [d for d in dicts if some_key in d] 

>>> dict1 = {"hey":123} 
>>> dict2 = {"wait":456} 
>>> get_dicts_with_key('hey', dict1, dict2) 
[{'hey': 123}] 
>>> get_dicts_with_key('wait', dict1, dict2) 
[{'wait': 456}] 
>>> get_dicts_with_key('complaint', dict1, dict2) 
[] 

키 중 하나 딕셔너리에 존재한다면, 모두 같은 반환됩니다 :

>>> dict1['complaint'] = 777 
>>> dict2['complaint'] = 888 
>>> get_dicts_with_key('complaint', dict1, dict2) 
[{'complaint': 777, 'hey': 123}, {'complaint': 888, 'wait': 456}] 
>>> 
+1

'dict'유형을 섀도 잉하지 않으려면 목록 이해에서'dict '를'd'로 변경하십시오. –

+0

좋은 전화. –

관련 문제