1

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?

AndriiL
  • 89
  • 1
  • 6

2 Answers2

1

It appears that the line matchdict=dict.fromkeys(ref, []) is using a reference to the same list for each key. As stated in this answer, you can use a dict comprehension like this:

matchdict={key: list() for key in ref}

Community
  • 1
  • 1
horns
  • 1,843
  • 1
  • 19
  • 26
0

Alternatively, you can create and assign a list after the dictionary initialization:

def compareItemsInLists(ref, searchlist):
    matchdict=dict.fromkeys(ref, None)
    for item in ref:
        list1 = []
        for stitem in searchlist:
            if item in stitem:
                print "Key %s matches string %s" %(item,stitem) 
                list1.append(stitem)
        matchdict[item] = list1
    return matchdict
Moshe Carmeli
  • 295
  • 1
  • 5