Reputation: 39
How do I create a dictionary where every key is a value from a list, and every value is all the values from the list except the key?
Example:
if I had
lst = [1, 2, 3, 4, 5, 6]
how would I create the dictionary I described using for loops?
d = {1: [2,3,4,5,6], 2: [1,3,4,5,6], 3: [1,2,4,5,6], 4: [1,2,3,5,6]}
I want to be able to do this using a for loop, but I don't even know where to start.
Upvotes: 3
Views: 1804
Reputation: 20434
You can do this in one line with a dictionary comprehension
:
d = {i:[e for e in lst if e != i] for i in lst}
which, for your example, gives:
{1: [2, 3, 4, 5, 6], 2: [1, 3, 4, 5, 6], 3: [1, 2, 4, 5, 6], 4: [1, 2, 3, 5, 6], 5: [1, 2, 3, 4, 6], 6: [1, 2, 3, 4, 5]}
Upvotes: 1
Reputation: 6348
This sounds like homework, so I'm only going to give you the outline of a solution:
copy.deepcopy
in the standard library to copy the list.Extra credit:
Upvotes: 2