python - can I compare the keys of two dictionaries that are not in the same order? -


i apologize must basic question using dictionaries. i'm learning python, , objective have compare 2 dictionaries , recover key , value entries both entries identical. understand order in dictionaries not relevant if 1 working list. adopted code compare dictionaries , wanted make sure order of dictionaries not matter.

the code have written far is:

def compare_dict(first,second):      open('common_hits_python.txt', 'w') file:              keyone in first:                  keytwo in second:                      if keytwo == keyone:                          if first[keyone] == second[keytwo]:                              file.write(keyone + "\t" + first[keyone] + "\n")  

any recommendations appreciated. apologize redundany in code above. if confirm comparing 2 dictionaries way not require key in same order great. other ways of writing function appreciated well.

since loop on both dictionaries , compare combinations, no, order doesn't matter. every key in 1 dictionary compared every key in other dictionary, eventually.

it not efficient way test matching keys, however. testing if key present simple keyone in second, no need loop on keys in second here.

better still, can use set intersections instead:

for key, value in first.viewitems() & second.viewitems():     # loops on key - value pairs match in both.     file.write('{}\t{}\n'.format(key, value))  

this uses dictionary view objects; if using python 3, can use first.items() & second.items() dictionaries there return dictionary views default.

using dict.viewitems() set works if values hashable too, since treating values strings when writing file assumed were.

if values not hashable, you'll need validate values match, can still use views , intersect keys:

for key in first.viewkeys() & second.viewkeys():     # loops on keys match in both.     if first[key] == second[key]:         file.write('{}\t{}\n'.format(key, first[key]))  

again, in python 3, use first.keys() & second.keys() intersection of 2 dictionaries keys.


Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -