比较字典中的项目字典

时间:2013-05-03 22:42:59

标签: python dictionary comparison

我一直在研究这个问题似乎很长一段时间。我有一个字典,看起来像这样:

{'1': {'Lady in the Water': 2.5, 'Snakes on a Plane': 3.5, 'Just My Luck': 3.0, 'Superman Returns': 3.5, 'You, Me and Dupree': 2.5,'The Night Listener': 3.0}, '2': {'Lady in the Water': 3.0, 'Snakes on a Plane': 3.5,'Just My Luck': 1.5, 'Superman Returns': 5.0, 'The Night Listener': 3.0,'You, Me and Dupree': 3.5},'3': {'Lady in the Water': 2.5, 'Snakes on a Plane': 3.0,'Superman Returns': 3.5, 'The Night Listener': 4.0}}

实际上事情要大得多,但我想要找到的是列表或设置与至少有2部电影相互共同的id。但是有些东西一定是错的,因为第一个密钥必须用第二个密钥检查,然后是第一个密钥和第三个密钥,直到密钥用完,然后是第二个密钥和第三个密钥,依此类推,直到我没有更多的密钥。然后是第三把钥匙的转弯。

最后,我想只获得至少有2部电影的按键。

我试过这样做:

def sim_critics(movies):
    similarRaters=set()

    first=1
    lastCritic= ''

    movie_over = collections.defaultdict(list)
    movCount=Counter(movie  for v in movies.values() for movie in v)

    for num in movies:
        for movie, _ in movies[num].items():
            movie_over[movie].append(num)


    for critic,_ in movie_over.items():
        if first!=1:
            critic_List = collections.Counter(movie_over[critic])
            critic2_list = collections.Counter(movie_over[lastCritic])
            overlap = list((critic_List & critic2_list).elements())

            if len(overlap) >= 2:
                key = critic + " and " + lastCritic 
                similarRaters.add(key)  
        lastCritic= critic
        first=2  
    return similarRaters

1 个答案:

答案 0 :(得分:1)

一个简单的解决方案就是:

def simCritics(movies):
    matchingDicts = set()
    for m in movies:
        for i in movies:
            if (len(m) + len(i)) > len(set(m).union(i)):
                matchingDicts.add((m, i))

    myList = [i for i in list(matchingDicts) if i[0] != i[1]]

    myL = []
    for i in myList:
        if (i[1], i[0]) in myL:
            continue
        myL.append(i) 
    return myL

中间的比较(比较len的比较)是至关重要的,因为如果电影重叠,它们将至少有一个相同的键,因此联合(删除重复)将小于总和。