简体   繁体   English

比较python列表中的两个字典

[英]Comparing two dictionaries in list in python

I don't know how to write the script for comparing two dictionary which are present in a list even though i don't know the dictionary names as well 我不知道如何编写用于比较列表中存在的两个字典的脚本,即使我也不知道字典名称也是如此

sample code: Am i correct or not? 示例代码:我正确还是不正确? if no then please help me to find the solution Here "dct_list_cluster" is list which contains two dictionaries 如果不是,请帮助我找到解决方案。这里的“ dct_list_cluster”是包含两个字典的列表

code: 码:

for count in range(len(dct_list_cluster)):
  if dct_list_cluster[count].keys() in dct_list_cluster[count+1].keys():
     fo = open("cluster_" + str(ip_list[count]) + "_output.txt", "a")
     fo.write("\n=> %s" % (dct_list_cluster[key])

If I got you right 如果我说对了

You could use list comprehension 您可以使用list comprehension

code: 码:

lst=[{"a":2,"b":3,"c":4},{"b":4}]
[a for a in lst[0] if a in lst[1]]
['b']

Doing it with out list comprehension 做到无list comprehension

code: 码:

lst=[{"a":2,"b":3,"c":4},{"b":4}]
for a in lst[0]:
    if a in lst[1]]:
        print a

output: 输出:

b

Operation: 操作:

1.When you are looping over the dictionary you are looping over the keys of the dictionary there are methods to loop over value and both keys and value 1,当您遍历字典时,您遍历字典的键时, there are methods to loop over value and both keys and value

2.Seeing if it is available in second dictionary if so printing it 2.查看是否在第二本词典中可用

edit: 编辑:

lst=[{"a":2,"b":3,"c":4},{"b":4},{"b":2,"d":6},{"d":4}]


for count in range(len(lst)-1):
   for a in lst[count]:
      if a in lst[count+1]:
         print "dic"+str(count)+"\t"+str(a)+"\tis common to next dic"

output: 输出:

dic0    b       is common to next dic
dic1    b       is common to next dic
dic2    d       is common to next dic

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM