【发布时间】:2019-04-23 23:57:28
【问题描述】:
我有两个包含字典的列表。我想比较这些字典中的某些字段。
current_list = [{"name": "Bill","address": "Home", "age": 23, "accesstime":11:14:01},
{"name": "Fred","address": "Home", "age": 26, "accesstime":11:57:43},
{"name": "Nora","address": "Home", "age": 33, "accesstime":11:24:14}]
backup_list = [{"name": "Bill","address": "Home", "age": 23, "accesstime":13:34:24},
{"name": "Fred","address": "Home", "age": 26, "accesstime":13:34:26},
{"name": "Nora","address": "Home", "age": 33, "accesstime":13:35:14}]
列表/字典的顺序应该相同,我只想比较某些键值对。就像姓名、地址、年龄和忽略访问时间一样,但到目前为止我所拥有的是比较每个密钥/对。所以我只是想比较一下
current_list:dictionary[0][name] -> backup_list:dictionary[0][name] and then
current_list:dictionary[0][address] -> backup_list:dictionary[0][address]
等等。
for x in current_list:
for y in backup_list:
for k, v in x.items():
for kk, vv in y.items():
if k == kk:
print("Match: {0}".format(kk))
break
elif k != kk:
print("No match: {0}".format(kk))
电流输出
Match name with name
No Match address with name
Match address with address
No Match age with name
No Match age with address
Match age with age
No Match dateRegistered with name
No Match dateRegistered with address
No Match dateRegistered with age
Match dateRegistered with dateRegistered
首选输出
Match name with name
Match address with address
Match age with age
* 由于需求更改,我的列表变成了 Elementtree xml 元素的列表 *
所以不是上面的列表,而是变成了
backup_list = ["<Element 'New' at 0x0000000002698C28>, <Element 'Update' at 0x0000000002698CC8>, <Element 'New' at 0x0000000002698CC8>"]
ElementTree 是一个 xml 元素,其中包含:
{"name": "Nora", "address": "Home", "age": 33, "dateRegistered": 20140812}"
所以到目前为止,根据以下答案,这似乎满足了我的要求:
value_to_compare = ["name", "address", "age"]
for i, elem in enumerate(current_list):
backup_dict = backup_list[i]
if elem.tag == "New":
for key in value_to_compare:
try:
print("Match {0} {1} == {2}:".format(key, backup_dict.attrib[key], elem.attrib[key]))
except KeyError:
print("key {} not found".format(key))
except:
raise
else:
continue
【问题讨论】:
-
我刚刚发现我不能使用字典列表,因为我必须考虑其他一些标准。所以它实际上必须是一个 xml 元素列表。 [,,]。 RomainL 的解决方案接近我所需要的。
标签: python list dictionary