2016-07-05 3 views
3

나는 dict 값에 특정 키에 [Complted]이 들어 있는지 확인해야하는 간단한 조건이 있습니다.dict 값에 단어/문자열이 포함되어 있는지 확인하는 방법은 무엇입니까?

예를 :

나는 Description 키를 시작으로 그 안에 [Complted] 포함 된 경우 확인해야
'Events': [ 
       { 
        'Code': 'instance-reboot'|'system-reboot'|'system-maintenance'|'instance-retirement'|'instance-stop', 
        'Description': 'string', 
        'NotBefore': datetime(2015, 1, 1), 
        'NotAfter': datetime(2015, 1, 1) 
       }, 
      ], 

. 즉

'Descripton': '[완료] 인스턴스가 저하 하드웨어에서 실행되는'내가 그렇게 할 수있는 방법

?

if inst ['Events'][0]['Code'] == "instance-stop": 
     if inst ['Events'][0]['Description'] consists '[Completed]": 
       print "Nothing to do here" 
+1

이 줄 어떻게해야 무엇 :

은이 방법을 시도? '코드': '인스턴스 재부팅'| '시스템 재부팅'| '시스템 유지 관리'| '인스턴스 중지'| '인스턴스 중지' – sidney

+1

잠재적 인 복제본을 왜 downvote합니까? 그는 충분한 세부 사항을 가지고 질문을하기에 충분히주의를 기울였습니다. –

+0

@HarshTrivedi 아마도 "이 질문은 연구 노력을 보이지 않습니다 ..."* 때문에? – SiHa

답변

1

등이 검색됩니다. consists 대신 in을 사용해야합니다. 파이썬에는 consists이라는 이름이 없습니다.

if inst['Events'][0]['Code'] == "instance-stop": 
     if '[Completed]' in inst['Events'][0]['Description'] 
      # the string [Completed] is present 
      print "Nothing to do here" 

는 희망이 도움이 : 코드에서 그래서

"ab" in "abc" 
#=> True 

"abxyz" in "abcdf" 
#=> False 

)

+0

'in'은 키워드가 아니라 메소드입니다. – sidney

+1

'! = None'을 검사 할 필요가 없으며 검사하는 올바른 방법이 아닙니다. 그것은'아니다 '이어야한다. – RedX

0
for row in inst['Events']: 
    if ("instance-stop" in row['Code'].split('|')) and ((row['Descripton'].split(' '))[0] == '[Completed]'): 
     print "dO what you want !" 
1

나는이가 'Events' 키가을 가지고 보는

elif inst ['Events'][0]['Code'] == "instance-stop": 
         if "[Completed]" in inst['Events'][0]['Description']: 
          print "Nothing to do here" 
1

작동 발견 사전 목록 값을 사용하면 색인을 하드 코딩하는 대신 모든 항목을 반복 할 수 있습니다.

또한 제공된 예제에서 inst ['Events'][0]['Code'] == "instance-stop":은 사실이 아닙니다.

for key in inst['Events']: 
    if 'instance-stop' in key['Code'] and '[Completed]' in key['Description']: 
     # do something here 
관련 문제