创建一个新字典,使用循环对原始字典进行总结



数据集或给定的字典是:

# A list of video reviews
# - Each review has the name of the video, the numer of views
#   and a list of user reviews.
# - Each user review has the user's name and the review they gave
#   to the video.
video_reviews = [
{
"name": "Cats doing nothing",
"number_of_views": 450743,
"reviews": [
{"name": "Jeb", "review": 5},
{"name": "Samantha", "review": 2},
{"name": "Crystal", "review": 3},
]
},
{
"name": "All Fail",
"number_of_views": 1239734,
"reviews": [
{"name": "Crystal", "review": 5},
{"name": "Frank", "review": 3},
{"name": "Jeb", "review": 3},
]
},
{
"name": "Runaway Nintendo",
"number_of_views": 48343,
"reviews": [
{"name": "Samantha", "review": 4},
{"name": "Bill", "review": 3},
{"name": "Sarah", "review": 4},
]
},
]

这就是我的问题:我想定义一个函数并创建一个用户摘要——一个字典——其中键是用户的名字,值是他们查看的视频列表。预计结果如下:

{
"Jeb": ["Cats doing nothing", "All Fail"],
"Samantha": ["Cats doing nothing","Runaway Nintendo"],
"Crystal": ["Cats doing nothing", "All Fail"],
"Frank": ["All Fail"],
"Bill": ["Runaway Nintendo"],
"Sarah": ["Runaway Nintendo"],
}

目前,我的代码是:

def create_user_summary(video_reviews):
summary = {}
for video in video_reviews:
for person in video["reviews"]:
user = person["name"]
video_name = []
if person["name"] == user:
video_name.append(video["name"])
summary[user] = video_name
return summary
AssertionError: 
You returned:
{'Jeb': ['All Fail'], 'Samantha': ['Runaway Nintendo'], 'Crystal': ['All Fail'], 'Frank': ['All Fail'], 'Bill': ['Runaway Nintendo'], 'Sarah': ['Runaway Nintendo']}
instead of:
{'Jeb': ['Cats doing nothing', 'All Fail'], 'Samantha': ['Cats doing nothing', 'Runaway Nintendo'], 'Crystal': ['Cats doing nothing', 'All Fail'], 'Frank': ['All Fail'], 'Bill': ['Runaway Nintendo'], 'Sarah': ['Runaway Nintendo']}

如何修改我的代码并使输出与预期的匹配?

以下是您的代码的修改版本,我认为它可以满足您的需求:

def create_user_summary(video_reviews):
summary = {}
for video in video_reviews:
for person in video["reviews"]:
summary.setdefault(person["name"], []).append(video["name"])
return summary

结果";

{'Jeb': ['Cats doing nothing', 'All Fail'], 'Samantha': ['Cats doing nothing', 'Runaway Nintendo'], 'Crystal': ['Cats doing nothing', 'All Fail'], 'Frank': ['All Fail'], 'Bill': ['Runaway Nintendo'], 'Sarah': ['Runaway Nintendo']}

您可以为此使用一些python内置函数,如sortedgroupby,并将其与列表和dict理解粘合在一起:

from itertools import groupby
source = ((rev['name'], vid['name']) for vid in video_reviews for rev in vid['reviews'])
result = {k: list(m for _, m in g) for k, g in groupby(sorted(source), lambda x: x[0])}
print(result)

您可以使用defaultdict

from collections import defaultdict
result = defaultdict(list)
for item in video_reviews:
for review in item['reviews']:
result[review['name']].append(item['name'])
print(dict(result))

结果:

{'Jeb': ['Cats doing nothing', 'All Fail'],
'Samantha': ['Cats doing nothing', 'Runaway Nintendo'],
'Crystal': ['Cats doing nothing', 'All Fail'],
'Frank': ['All Fail'],
'Bill': ['Runaway Nintendo'],
'Sarah': ['Runaway Nintendo']}

相关内容

  • 没有找到相关文章