0

I'm trying to compare each dictionary key with a values from list:

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]

And result I'm getting:

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

But I would like to see

[]

Because matched keys are in dictionary.

4

2 回答 2

3

如果要列出字典match存在的键,请使用列表推导:

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

您的代码创建了 3 对,其中的每个元素之一match,以及来自 的 3 个任意order。如果这三个任意键碰巧不等于 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 回答