比较python列表中的词典

2024-10-01 17:25:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个嵌套字典的列表:

list1 = [{u'Key': u'lm_app', u'Value': u'lm_app'}, {u'Key': u'Name', u'Value': u'new Name'}, {u'Key': u'lm_sbu', u'Value': u'lm_sbu'}, {u'Key': u'lm_app_env', u'Value': u'lm_app_env'}]

list 2 = [{u'Key': 'lm_sbu', u'Value': 'lm_sbu'}, {u'Key': 'Name', u'Value': 'test'}]

如何检查列表1中的键是否存在于列表2中?你知道吗

对于本例,键“lm泷sbu”和“Name”都存在于列表1和列表2中。但是,键“lm\u app”和“lm\u app\u env”存在于列表1中,而不存在于列表2中。你知道吗

一旦我发现了差异,我想把差异附加在一个单独的列表中。你知道吗

谢谢


Tags: keynametestenvapp列表new字典
3条回答

Python集有助于:

list1 = [{u'Key': u'lm_app', u'Value': u'lm_app'}, {u'Key': u'Name', u'Value': u'new Name'}, {u'Key': u'lm_sbu', u'Value': u'lm_sbu'}, {u'Key': u'lm_app_env', u'Value': u'lm_app_env'}]
list2 = [{u'Key': 'lm_sbu', u'Value': 'lm_sbu'}, {u'Key': 'Name', u'Value': 'test'}]

list1_keys = {dictionary['Key'] for dictionary in list1}
list2_keys = {dictionary['Key'] for dictionary in list2}

print 'Keys in list 1, but not list 2: {}'.format(list(list1_keys - list2_keys))
print 'Keys in list 2, but not list 1: {}'.format(list(list2_keys - list1_keys))

输出:

Keys in list 1, but not list 2: [u'lm_app', u'lm_app_env']
Keys in list 2, but not list 1: []

类似于这样的,在itemlist中搜索的项目。使用库可以实现这一点,但我喜欢vanilla python。你知道吗

a = [i for j in [l.items() for l in list2] for i in j]
print "\n".join(filter(lambda item: item in a, itemlist))

实际上,您正在检查值(而不是键)之间的差异,在这种情况下,您可以将list1中的字典值与list2中的字典值进行比较:

s = {v for d in list1 for v in d.values()}.difference(*[d.values() for d in list2])
print s
# set([u'new Name', u'lm_app', u'lm_app_env'])

相关问题 更多 >

    热门问题