Reputation: 59
I want to create a dict with dict comprehension where self.students[i]
are some names and j
should be 0,2,4,6,8.
Right now x
returns
{'Patricia': 6, 'Roger': 6, 'Samantha': 6, 'Xander': 6}
What I want it to return is
{'Patricia': 0, 'Roger': 2, 'Samantha': 4, 'Xander': 6}`
Here is the code
x = {self.students[i] : j for i in range(0,len(self.students)) for j in range(0,len(self.students)+3, 2)}
Upvotes: 2
Views: 100
Reputation: 86
Your current code is looping through every student every time.
Hence on the last loop, when j = 6
, all of the values are changed to 6
.
Upvotes: 0
Reputation: 73
This works
students = ['Ivan', 'Masha', 'Sasha']
students_dict = {i: k*2 for k, i in enumerate(students)}
print(students_dict)
What you were doing was looping twice. This is used for making 2 dimensional lists. To understand your old code better, see here
Upvotes: 0
Reputation: 42143
You could use zip to build the dictionary from its keys combined with an even number counter (from itertools):
x = dict(zip(self.students,itertools.count(0,2)))
Upvotes: 0
Reputation: 71424
zip
the range with the list to get pairs of values, instead of using nested for
loops (which are overwriting each value in turn across the entire dict, leaving you with only the last value of j
):
>>> students = ['Patricia', 'Roger', 'Samantha', 'Xander']
>>> {s: j for s, j in zip(students, range(0, len(students) * 2, 2))}
{'Patricia': 0, 'Roger': 2, 'Samantha': 4, 'Xander': 6}
Upvotes: 0
Reputation: 227200
You don't need to use range
when looping over a list, you can just loop over the list itself. Also, you don't need to use a 2nd loop for j
, you can just calculate your number based off of the index in the list.
To get the indexes as you loop, you can use enumerate
.
x = {student:i*2 for i,student in enumerate(self.students)}
Upvotes: 3
Reputation: 350034
Use enumerate
:
x = {student : i * 2 for i, student in enumerate(self.students)}
Upvotes: 5