3

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.

Valeriy
  • 1,365
  • 3
  • 18
  • 45
no mo
  • 39
  • 1
  • 4
    This looks like homework. Please review the guidelines here about posting homework questions https://meta.stackoverflow.com/a/334823/4138919. If it is not homework, please make a reasonable attempt and provide an update on what you've tried. A `for loop` seems like a reasonable place to start. I would review some documentation about Python lists (e.g. https://developers.google.com/edu/python/lists), dictionaries, and basics of iteration/list enumeration. – VIN Nov 23 '17 at 19:29
  • This is actually cute in Haskell. Haskell uses association lists instead of dictionaries ([most of the time](https://hackage.haskell.org/package/containers-0.5.10.2/docs/Data-Map.html)) which are basically just tuples of `(key, value)`, so you can do `result xs = [(x, filter (/=x) xs) | x <- xs]` (where `(/=)` is the "not equal to" function and ` | x <- xs` is equivalent to `for x in xs`) – Adam Smith Nov 24 '17 at 20:19

2 Answers2

2

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?
Ben
  • 5,952
  • 4
  • 33
  • 44
1

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]}
Joe Iddon
  • 20,101
  • 7
  • 33
  • 54
  • 1
    Doesn't that break when the list isn't a range of consecutive numbers starting with 0? – Ben Nov 24 '17 at 14:31
  • @Ben Yes you are entirely write, there was confusion on my part. I have updated the answer now, and it is actually a shorter expression now! – Joe Iddon Nov 24 '17 at 17:40