List Comprehension
- Inside the comprehension, we get to set the new_key, the new_value, and we get to loop through items in a list.
- So any sort of iterable; a list, a range, a string, anything you want.
#Creating a dictionary using this shortened syntax.
new_dict = {new_key: new_value for item in list}
- We could also create a new dictionary based on the values in an existing dictionary.
- We could take that dictionary and then get hold of all of the items inside that dictionary, and then split it into a key and a value.
#Keyword Method
new_dict = {new_key: new_value for (key,value) in dict.items()}
Conditional Dictionary Comprehension
new_dict = {new_key: new_value for (key,value) in dict.items() if test}
names = ['Alex', 'Beth', 'Caroline', 'Dave', 'Eleanor', 'Freddie']
import random
students_scores = {student:random.randint(1, 100) for student in names}
---------
{'Alex': 80, 'Beth': 79, 'Caroline': 62, 'Dave': 67, 'Eleanor': 44, 'Freddie': 73}
names = ['Alex', 'Beth', 'Caroline', 'Dave', 'Eleanor', 'Freddie']
students_scores = {'Alex': 80, 'Beth': 79, 'Caroline': 62, 'Dave': 67, 'Eleanor': 44, 'Freddie': 73}
#passed_student = {student: students_scores[student] for student in students_scores if students_scores[student] >= 60}
#Angela's method
passed_student = {student:score for (student,score) in students_scores.items() if score >= 60}
---------
{'Alex': 80, 'Beth': 79, 'Caroline': 62, 'Dave': 67, 'Freddie': 73}