[英]How to create unique key(keys defined in some list) for dictionary and assign value to it in for loop in python 2.7?
[英]How to get keys by value in dictionary (python 2.7)
我有这个描述学生课程的字典:键是名字(字符串),值是课程列表(字符串)
students_dict={"name1":["math","computer science", "statistics"],"name2":["algebra","statistics","physics"],"name3":["statistics","math","programming"]}
我想创建一个获取此dictionery并返回一个新函数的函数:键将是课程(字符串),值将是参加此课程的学生姓名列表(srtings列表)
course_students={"statistics":["name1","name2","name3"],"algebra":["name2"],"programming":["name3"],"computer science":["name1"],"physics":["name2"],"math":["name1","name3"]}
顺序无所谓。
编辑:这是我想要做的事情
def swap_student_courses(students_dict):
students_in_each_cours={}
cours_list=[...]
cours_names=[]
for cours in cours_list:
if students_dict.has_key(cours)==True:
cours_names.append(...)
students_in_each_cours.append(cours_names)
return students_in_each_cours
为了简单起见,我会在这里使用defaultdict
,但要知道你可以用常规字典完成相同的操作:
from collections import defaultdict
students_dict={"name1":["math","computer science", "statistics"],
"name2":["algebra","statistics","physics"],
"name3":["statistics","math","programming"]}
course_students = defaultdict(list)
for name, course_list in students_dict.items():
for course in course_list:
course_students[course].append(name)
它可以通过集合理解(首先获得一组独特的课程名称),然后是字典理解(将课程名称与该课程出现在各自列表中的学生列表相关联)来完成:
all_courses = {course for student_course_list in students_dict.values() for course in student_course_list}
course_students = {course:[student_name for student_name,student_course_list in students_dict.items() if course in student_course_list] for course in all_courses}
您尝试过的方法忽略了搜索每个学生的课程列表:您使用students_dict.has_key(cours)
忘记了学生姓名,而不是课程,是students_dict
的关键。
这是您可以使用的简单功能。
from collections import defaultdict
def create_new_dict(old_dict):
new_dict = defaultdict(list)
for student, courses in old_dict.items():
for course in courses:
new_dict[course].append(student)
return new_dict
python标准dict和defaultdict之间的唯一区别是,如果您尝试访问标准dict中的非现有密钥,它将导致KeyError
而在defaultdict中,它将为该密钥设置默认值,以创建该dict时传递的任何内容。 在我们的例子中它的空列表。
没有defaultdict的实现
def create_new_dict(old_dict):
new_dict = dict()
for student, courses in old_dict.items():
for course in courses:
try:
new_dict[course].append(student)
except KeyError:
new_dict[course] = [student]
return new_dict
编辑 - -
KeyError在标准字典中提升,因为如果它是我们第一次尝试访问某些键,例如'math'
,它就不在字典中。 这是词典的优秀解释。
值重复不是问题,因为在这种情况下我们只是将新学生附加到列表中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.