0
dict_list={"a":1,"b":2,"c":3}
inverse_dict=dict([val,key] for key,val in dict_list.items())

The for loop statements I have learned all start with for. I don't understand why there is a list before the keyword for in this statement, and I don't know how this statement can reverse the key-value pairs of the dictionary.

fjybiocs
  • 59
  • 5
  • Note that if you want to read up on things, it's important to separate *statements* – things standing on their own on the start of a "line" – from *expressions* – things that make up other things. The weird ``for`` thing you are seeing is in the [expression specification](https://docs.python.org/3/reference/expressions.html#displays-for-lists-sets-and-dictionaries). – MisterMiyagi Jan 26 '22 at 07:05
  • Yes, this isn't a for-loop statement at all! It is a generator expression, which works like list, dict, and set comprehensions. They are not statements, they are expressions, they evaluate to a value. Essentially these create iterables (generator, list, dict, or set) of various types and allow you to use arbitrarily nested mapping/filtering operations – juanpa.arrivillaga Jan 26 '22 at 07:24

1 Answers1

3
inverse_dict = dict([val, key] for key, val in dict_list.items())
                    #---generator expression-------------------#
                    #--pair--#

works by virtue of dict() accepting an iterable of pairs to turn into a dictionary; the whole (x for y in z) production is a generator expression that yields an iterable.

In the expression, the [val, key] expression forms a key-value pair for each pair in items.
(It would be more idiomatic to use a tuple ((val, key)) instead of a list.)

The modern idiom for this is a dictionary comprehension, which is clearer to read:

dict_list = {"a": 1, "b": 2, "c": 3}
inverse_dict = {val: key for key, val in dict_list.items()}
AKX
  • 152,115
  • 15
  • 115
  • 172