0

New to python, and am learning about dict comprehension online. i saw this snippet of code but do not understand how it work.

enter image description here

i understand this dict comprehension {k: D[k] for k in D.keys() but please help me understand - removeKeys}. I do not understand how the result to be. Thank you for your feedback

trt
  • 1
  • 2

1 Answers1

0

First, let's understand list comprehension.

List Comprehension:

x = [i for i in range(10)]
>>> Output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Now, similary in dict comprehension we use the same syntax. However, dicts have key: value pairs and hence that's how you need to do it.

Dict Comprehension: What the above code is doing:

  • Get the keys of D dict and remove the keys 0, 2, 5.
  • Iterate over the remaining keys and generate a key: value based on D dict.
The Myth
  • 1,090
  • 1
  • 4
  • 16
  • thanks for comment. but how does it remove keys `0, 2, 5`? – trt Nov 13 '22 at 07:57
  • `D.keys()` returns a `list` of the keys of the `D` dict. And, you can subtract two lists. So, `D.keys() - removeKeys` simply does this: `[0, 1, 2, 3, 4, 5] - [0, 2, 5`. Please mark the answer correct if it helped you :) – The Myth Nov 13 '22 at 07:58
  • 1
    You can *not* subtract two lists. You can however do subtraction with sets, and `dict.keys()` returns a set-like view. – deceze Nov 13 '22 at 08:15
  • so `{k: D[k] for k in D.keys() - removeKeys}` under the hood is `list(set(dict.keys() - set(removeKeys))` ? – trt Nov 13 '22 at 08:27
  • @trt Sort of but not really. `dict.keys()` returns an object (a key view) which supports the `-` operator. As the right-hand-side of that `dict.keys() -` operations, it appears to take any *iterable*. I.e. conceptually it's defined as `set() - set()`, but in practice it's implemented more leniently as *set-like minus any-iterable*. – deceze Nov 13 '22 at 08:31