简体   繁体   中英

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

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

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

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

2.Seeing if it is available in second dictionary if so printing it

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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