两个列表的比较导致字典中有重复项

Comparison of two lists results in dictionary with duplacated items

我正在尝试创建用于比较两个列表中的项目的函数,如果列表中的字符串甚至部分匹配,则写出类似 {item_list1_as_key:item_list2_as_value} 的结果。这个函数看起来像:

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"]

但是,我得到了 return 像这样的东西:

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']}

看起来比较效果很好,但我看不出 .append 函数有什么问题。为什么它会在 searchlist 和不匹配的项目中写入重复项?

matchdict=dict.fromkeys(ref, []) 行似乎为每个键使用了对同一列表的引用。如 this answer 中所述,您可以像这样使用字典理解:

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

或者,您可以在字典初始化后创建并分配一个列表:

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