I'm trying to make function for comparison of items in two lists and write result like {item_list1_as_key:item_list2_as_value}
if strings in list have even partial match. This function looks like:
def compareItemsInLists(ref, searchlist):
matchdict=dict.fromkeys(ref, [])
for item in ref:
for stitem in searchlist:
if item in stitem:
print "Key %s matches string %s" %(item,stitem)
matchdict[item].append(stitem)
return matchdict
ref=["a","b","c"]
searchlist=["aaa","bab","cbc","ddd"]
However, I got return something like these:
Key a matches string aaa
Key a matches string bab
Key b matches string bab
Key b matches string cbc
Key c matches string cbc
{'a': ['aaa', 'bab', 'bab', 'cbc', 'cbc'],
'c': ['aaa', 'bab', 'bab', 'cbc', 'cbc'],
'b': ['aaa', 'bab', 'bab', 'cbc', 'cbc']}
Looks like comparison works well, but I can't catch what is wrong with .append
function. Why it writes duplicates of items in searchlist
and non-matched items?