アップデート
python2.7 および python3.x では、より良い方法があります。
items = ((k,v) for (k,v) in requestDicts.__dict__.items() if k.startswith('dictref'))
r_items = recievedDict.viewitems()
print next(k for k,sub in items if len(sub.viewitems() & r_items) == len(sub))
最初の行は、クラス保持辞書をもう少し便利なデータ構造にしようとする試みです。2 行目は単に 3 行目を短くし、ジェネレーターでの余分な属性検索/メソッド呼び出しを避けるためのものです。
python3.x では、python2.x で行ったdict.items
のと同じことを返します。dict.viewitems
それはそれで2to3
わかると思います。基本的に、view
はアイテムをセットのようなオブジェクトとして返します。2 つのセットの交差を取得し、それが完全な交差であることを確認します。つまり、一方の辞書が他方の辞書のサブセットであることを確認します。これが私の他の回答よりも効率的であることを保証するものではありませんが、もう少し簡潔です (より高速であっても驚かないでしょう)。私たちはtimeit
知る必要があると思います。
それらを比較するためにループするよりも良い方法はありません:
def compare(sub,full):
try:
return all(sub[k] == full[k] for k in sub)
except KeyError:
return False #sub's keys aren't a subset of full's keys.
どれが最初に一致するかを判断するには、次のようにします。
next(sub for sub in (dictrefA,dictrefB,dictrefC) if compare(sub,recievedDict))
完全で具体的な作業例を次に示します。
class requestDicts():
dictrefA={
"operation_module":"cbs",
"operation_group":"xxx",
"operation_type":"yyy"}
dictrefB={
"operation_module":"cbs",
"operation_group":"xxx",
"operation_type":"yyy1"}
dictrefC={
"operation_module":"cbs",
"operation_group":"xxx1",
"operation_type":"yyy1"}
recievedDict={
"msg_id":100,
"operation_module":"cbs",
"operation_group":"xxx",
"operation_type":"yyy1",
"user_name":"venkat",
"msg_length":50}
def compare(sub,full):
try:
return all(sub[k] == full[k] for k in sub)
except KeyError:
return False #sub's keys aren't a subset of full's keys.
items = ((k,v) for (k,v) in requestDicts.__dict__.items() if k.startswith('dictref'))
print next(k for k,sub in items if compare(sub,recievedDict))