0

各辞書キーをリストの値と比較しようとしています:

order = {
    u'custom_attributes_desc': {u'text': u'Food truck', u'name': u'Bob', u'email': u'bob@yahoo.com'}, 
    u'account_id': 12345, 
    u'state_desc': u'open', 
    u'start_dt': u'2013-07-25 15:41:37', 
    u'end_dt': u'2013-07-25 19:41:37', 
    u'product_nm': u'foo', 
    u'transaction_id': 12345, 
    u'product_id': 1111
}
match = ['transaction_id', 'account_id', 'product_nm']
not_matched_keys = [key_match for key_order, key_match in zip(order.keys(),match) if key_order != key_match]

そして、私が得ている結果:

not_matched_keys
['transaction_id', 'account_id', 'product_nm']

しかし、私は見たいです

[]

一致したキーは辞書にあるためです。

4

2 に答える 2

3

ディクショナリに存在しないmatchものから取得したキーを一覧表示する場合は、リスト内包表記を使用します。

not_matched_keys = [key for key in match if key not in order]

あなたのコードは、 のmatch3 つの任意のキーを使用して、 の各要素の 1 つである 3 つのペアを作成しましたorder。これらの 3 つの任意のキーがたまたま 3 つの値と等しくない場合、matchそれらすべてが出力に含まれます。

>>> order = {u'custom_attributes_desc': {u'text': u'Food truck', u'name': u'Bob', u'email': u'bob@yahoo.com'}, u'account_id': 12345, u'state_desc': u'open', u'start_dt': u'2013-07-25 15:41:37', u'end_dt': u'2013-07-25 19:41:37', u'product_nm': u'foo', u'transaction_id': 12345, u'product_id': 1111}
>>> match = ['transaction_id', 'account_id', 'product_nm']
>>> list(zip(match, order.keys()))
[('transaction_id', 'end_dt'), ('account_id', 'product_id'), ('product_nm', 'transaction_id')]
于 2013-07-30T13:49:20.473 に答える
1

ここでも使えfilter()ます。

>>> filter(lambda x: x not in order, not_matched_keys)
[]
于 2013-07-30T13:50:02.620 に答える