0
data1=[{'aa': None, 'bb': 'dffg', 'cc': '0', 'dd': '1234', 'ee': None}, 
{'aa': 'cdfg', 'bb': None, 'cc': '0', 'dd': 'sc12', 'ee': 'edft'},
{'aa': 'bvkjdi', 'bb': 'hdjd', 'cc': '0', 'dd': None, 'ee': None},
{'aa': None, 'bb': None, 'cc': '0', 'dd': '123dg', 'ee': 'hddk'}]


data2={'aa': ('','cdfg', 'bvkjdi', ''), 'bb': ('dffg','', 'hdjd', ''),
'cc': ('0', '0', '0','0'), 'dd': ('1234', 'sc12', '','123dg'),
'ee': ('', 'edft', '','hddk') }

data1 是许多字典及其键值的列表,data2 是字典及其键值。需要比较这两个但格式不同。需要找出简单的方法来比较 data1 的 'aa' 和 'aa' data2 , data1 的 'bb' 值到 data2 的 'bb' 值同样适用于其余的东西。请帮我比较一下。

4

3 回答 3

0

您可以执行以下操作:

>>> data1_like_data2 = {}
>>> for item in data1:
...     for key in item:
...         try:
...             data1_like_data2[key] += (item[key],)
...         except:
...             data1_like_data2.update({key:(item[key],)})
>>> data1_like_data2
{'aa': (None, 'cdfg', 'bvkjdi', None), 'cc': ('0', '0', '0', '0'), 'dd': ('1234', 'sc12', None, '123dg'), 'ee': (None, 'edft', None, 'hddk'), 'bb': ('dffg', None, 'hdjd', None)}

然后直接对比,

>>> data1_like_data2 == data2:
>>> False

由于 None 和 '0' 问题,它给出了 False。根据您的要求进行排序,然后它会起作用。

于 2013-07-18T12:18:45.870 回答
0

假设 None = '' 和 0 = '0' 我认为这是你想要的:

data1=[{'aa': None, 'bb': 'dffg', 'cc': 0, 'dd': '1234', 'ee': None}, 
{'aa': 'cdfg', 'bb': None, 'cc': 0, 'dd': 'sc12', 'ee': 'edft'},
{'aa': 'bvkjdi', 'bb': 'hdjd', 'cc': 0, 'dd': None, 'ee': None},
{'aa': None, 'bb': None, 'cc': 0, 'dd': '123dg', 'ee': 'hddk'}]


data2={'aa': ('','cdfg', 'bvkjdi', ''), 'bb': ('dffg','', 'hdjd', ''),
'cc': ('0', '0', '0','0'), 'dd': ('1234', 'sc12', '','123dg'),
'ee': ('', 'edft', '','hddk') }

results = {}
for key in data2:
    set1 = [x[key] for x in data1]
    set1 = [str(x) if x is not None else '' for x in set1]
    set2 = list(data2[key])

    results[key] = set1 == set2        
# results = {'aa': True, 'cc': True, 'dd': True, 'ee': True, 'bb': True}    
于 2013-07-18T12:21:38.420 回答
0

您可以重组data1看起来像data2使用字典理解:

>>> n = {k: tuple(d[k] for d in data1) for k in data2}
>>> n
{'aa': (None, 'cdfg', 'bvkjdi', None), 'cc': ('0', '0', '0', '0'), 
'dd': ('1234', 'sc12', None, '123dg'), 'ee': (None, 'edft', None, 'hddk'), 
'bb': ('dffg', None, 'hdjd', None)}

既然你想None匹配'',我们也可以转换它们:

>>> n = {k: tuple(d[k] if d[k] is not None else '' for d in data1) for k in data2}
>>> n
{'aa': ('', 'cdfg', 'bvkjdi', ''), 'cc': ('0', '0', '0', '0'), 
'dd': ('1234', 'sc12', '', '123dg'), 'ee': ('', 'edft', '', 'hddk'), 
'bb': ('dffg', '', 'hdjd', '')}

之后:

>>> n == data2
True

如果你只想比较aabb键/值对,你可以把它们拉出来:

>>> keys_to_compare = {'aa', 'bb'}
>>> d1 = {k: tuple(d[k] if d[k] is not None else '' for d in data1) for k in keys_to_compare}
>>> d2 = {k: v for k,v in data2.iteritems() if k in keys_to_compare}
>>> d1 == d2
True

或者就地比较它们:

>>> all(tuple(d[k] if d[k] is not None else '' for d in data1) == data2[k] for k in keys_to_compare)
True
于 2013-07-18T12:35:51.257 回答