迭代并比较第一项和字典中的所有项

2024-09-27 07:35:07 发布

您现在位置:Python中文网/ 问答频道 /正文

请帮忙,我好像找不到办法。我正在做一个网络科学项目,这是我与python的第三个项目。在

我需要将字典中的第一项与同一词典中的所有其他项进行比较,但我的其他项都是词典。在

例如,我有一个字典,它具有以下值:

{'25': {'Return of the Jedi (1983)': 5.0},
 '42': {'Batman (1989)': 3.0, 'E.T. the Extra-Terrestrial (1982)': 5.0},
 '8': {'Return of the Jedi (1983)': 5.0 },'542': {'Alice in Wonderland (1951)': 3.0, 'Blade Runner (1982)': 4.0}, '7': {'Alice in Wonderland (1951)': 3.0,'Blade Runner (1982)': 4.0}} 

所以我要看看钥匙25和42是否包含同一部电影《绝地归来》,如果25和8有相同的电影等等。我需要知道有多少电影是重叠的。在

这是字典的一个例子,整个字典包含1000个键,子字典也大得多。在

我尝试过迭代、比较字典、复制、合并、合并,但我似乎不明白如何才能做到这一点。在

救命啊!在

问题是我仍然不能比较这两个子字典,因为我需要找到至少有两个相同电影作为一个整体的键。在


Tags: ofthe项目in网络return字典电影
3条回答

您可以使用collections.Counter

>>> dic={'25': {'Return of the Jedi (1983)': 5.0}, '42': {'Batman (1989)': 3.0, 'E.T. the Extra-Terrestrial (1982)': 5.0}, '8': {'Return of the Jedi (1983)': 5.0 }}
>>> from collections import Counter
>>> c=Counter(movie  for v in dic.values() for movie in v)

>>> [k for k,v in c.items() if v>1] #returns the name of movies repeated more than once
['Return of the Jedi (1983)']
>>> c
Counter({'Return of the Jedi (1983)': 2,
         'Batman (1989)': 1,
         'E.T. the Extra-Terrestrial (1982)': 1})

要获取与每部电影相关的密钥,可以使用collections.defaultdict

^{pr2}$

我的答案只会返回一个包含'title',['offender1',...]对的字典,对于多次观看的电影,即不是'E.T. the Extra-Terrestrial (1982)',而是{}将被报告。这可以通过在解决方案中返回overlaps而不是字典理解的结果来改变。在

其中d是:

d = {'25': {'Return of the Jedi (1983)': 5.0},
     '42': {'Batman (1989)': 3.0, 'E.T. the Extra-Terrestrial (1982)': 5.0},
     '8': {'Return of the Jedi (1983)': 5.0 },
     '542': {'Alice in Wonderland (1951)': 3.0, 'Blade Runner (1982)': 4.0},
     '7': {'Alice in Wonderland (1951)': 3.0,'Blade Runner (1982)': 4.0}
     } 

以下内容:

^{pr2}$

产生:

>>> 
{'Blade Runner (1982)': ['7', '542'], 'Return of the Jedi (1983)': ['25', '8'], 'Alice in Wonderland (1951)': ['7', '542']}

代码背后的推理:

d中的每个条目表示id : { movie_title1: rating, movie_title2: rating }。现在假设movie_title1发生在与两个或多个单独的^{键相关联的值中。我们想储存

  1. 看过两次或两次以上的电影的move_title。在
  2. id的键,与在其中观看电影的关联。在

因此,我们希望得到这样的词典

{ move_title1: {'id1','id2'}, movie_title2: {'id2','id5'}

字典中并没有真正的“第一”项,但您可以通过以下方式找到包含给定电影的所有键:

movies = {}
for k in data:
    for movie in data[k]:
        movies.setdefault(movie, []).append(k)

输出影片如下所示:

^{pr2}$

相关问题 更多 >

    热门问题