no mo
no mo

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

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

Answers (2)

Joe Iddon
Joe Iddon

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

Ben
Ben

Reputation: 6348

This sounds like homework, so I'm only going to give you the outline of a solution:

  1. Create an empty dictionary
  2. Loop through the list and add its elements and a copy of the entire list to as the value to the dictionary. Use copy.deepcopy in the standard library to copy the list.
  3. Loop through the keys and values in your new dictionary and remove the key from the value.

Extra credit:

  • Use a dictonary comprehension(see towards the bottom of the section) to combine steps 1 and 2.
  • Learn the difference between shallow copies and deep copies. In this specific example, would you have been safe with a shallow copy?

Upvotes: 2

Related Questions