私の解決策は、辞書のリストを検索しようとしていることを前提としているため、リストを修正しました。リスト内の辞書に検索しているキーが含まれていないと、エラーが発生します。その目的のために、関数に単純なエラー処理を追加しました。
私はPythonの初心者ですから、私のものよりも洗練されたソリューションが存在するかもしれませんが、必要なものには十分かもしれません。このように動作します。値 '111'のキー '活動'の出現が見つかった場合、残りのリストは '値121'のキー '活動'の出現を検索されます。十分に簡単です。
、しかし、あなたは唯一の条件は、アクティビティ121は、アクティビティ111の発生後に非常に次の辞書で発見された場合、あなたは、単にライン14本に変更することができ会っ考慮する場合:
if i[key] == valueTwo and foundOne and (dictCount - 1) == countHelp:
また、アクティビティ111の後にアクティビティ121が最初に見つかった辞書を書き込もうとしているのか、辞書のリスト全体を書きたいのか分かりません。変数 'myDictionaries'は全体のリストで、変数 'i'はアクティビティ111の後でアクティビティ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)
私はコメント機能を使用するために十分なポイントを持っていないよう他の人は、それ以降のご質問のお手伝いをすることができます願っています。
このリストは辞書のような文字列を持つ1つの要素リストであることを意味しますか?それとも、辞書のリストになっていますか? – SO44
おそらくあなたの文字列に 'json.loads()'を使ってください。これにより、作業がより簡単で効率的になる辞書が返されます。 – IanAuld