내 솔루션은 사전 목록을 검색하려고한다는 가정하에 작성되었으므로 목록을 이와 같이 수정했습니다. 목록에있는 사전에 검색중인 키가 포함되어 있지 않으면 오류가 발생합니다. 그 목적을 위해 함수에 간단한 오류 처리를 추가했습니다.
저는 파이썬 초보자입니다. 따라서 제게는보다 우아한 해결책이 존재할 수 있지만, 필요한 것이면 충분할 수 있습니다. 그것은 다음과 같이 작동합니다 : '111'값을 가진 키 'activity'의 발생이 발견되면, 나머지리스트는 'value 121'키로 'activity'키의 발생을 검색합니다. 충분히 간단합니다. 또한,
if i[key] == valueTwo and foundOne and (dictCount - 1) == countHelp:
: 경우
은, 그러나, 당신은 단지 조건 활동 (121) 활동 (111)의 발생 후 바로 다음 사전에 발견되면, 당신은 단순히 라인 (14)이 변경할 수 있습니다 만났다 고려 나는 당신이 액티비티 111 후에 액티비티 121이 처음 발견 된 사전을 쓰려고하는지, 아니면 사전의 전체리스트를 쓰고 싶다면 확실하지 않다. 변수 'myDictionaries'는 전체 목록이고, 변수 'i'는 활동 121 후에 활동 121이 발견 된 첫 번째 사전입니다.
내 솔루션에서는 글을 쓰지 않고 목록을 인쇄합니다 파일로. 따라서 파일 쓰기 솔루션으로 변경하십시오.
# -*- coding: utf-8 -*-
from __future__ import print_function # You can remove this line if you're using Python 3.
def searchDictionaries(key, valueOne, valueTwo, myDictionaries): # Define the function with four arguments
dictCount = 0 # Initialize the count of dictionaries in the list
foundOne = False # Initialize the state for meeting the first condition
countHelp = 0 # This will help us determine if the second condition is met in the dictionary right after the first condition was met
for i in myDictionaries: # Start looping through the list of dictionaries
dictCount = dictCount + 1 # Increase count at every iteration
try:
if i[key] == valueOne: # Check if the first condition is met (if the value of activity is 111)
foundOne = True # Change the state of meeting the first condition to True
countHelp = dictCount # Keep this in case you want to modify the next line to only search in the next dictionary
if i[key] == valueTwo and foundOne: # Check if the second condition (activity value of 121) is present in any subsequent dictionary
# If you made it here, both conditions were met and you can write to file
print(myDictionaries) # Write the whole list of dictionaries to file. Use print(i) if you want to just print the first dictionary where you found 121 after 111 was found.
break # Stop searching
except Exception as e: # Error handling
print('Warning: %s - There is no key %s in dictionary %s.' % (e, e, dictCount))
return
# Your example list of dictionaries
myListOfDicts = [
{'activity': '111', 'interface': 'eds', 'clientIp': '12.207.212.130', 'logTime': 1469811993000},
{'session': -2147479722, 'dbCount': 33, 'totalHits': 24, 'query': 'TI', 'the': 'plague', 'searchedFrom': 'Unknown', 'searchType': 'And', 'logTime': 1469811994000},
{'activity': '121', 'customerId': 's8905647', 'groupId': 'main', 'profileId': 'eds'}
]
# Now you can call the function searchDictionaries with your desired values > key, first value, second value, name of your list of dictionaries
searchDictionaries('activity', '111', '121', myListOfDicts)
나는 내가 코멘트 기능을 사용하려면 포인트가 부족하지 않는 한 다른 사람이, 후속 질문에 당신을 도울 수 있기를 바랍니다.
이 목록을 사전과 비슷한 문자열이있는 요소 목록으로 사용 하시겠습니까? 아니면 사전 목록에 있어야하나요? – SO44
문자열에'json.loads()'를 사용해야 할 것입니다. 그러면 더 쉽고 효율적으로 사용할 수있는 사전이 반환됩니다. – IanAuld