0

For context, here is the entire snippet of code.

sample_dict = {1: 'r099', 2: 'g444', 3: 't555', 4: 'f444', 5: 'h666'}
print(sample_dict)
>>> {1: 'r099', 2: 'g444', 3: 't555', 4: 'f444', 5: 'h666'}

desired_order_list = [5, 2, 4, 3, 1]

reordered_dict = {k: sample_dict[k] for k in desired_order_list}
print(reordered_dict)
>>> {5: 'h666', 2: 'g444', 4: 'f444', 3: 't555', 1: 'r099'}

Could anyone explain this specific line of code for me? I don't understand the snytax.

reordered_dict = {k: sample_dict[k] for k in desired_order_list}

yatu
  • 86,083
  • 12
  • 84
  • 139
hadens
  • 1
  • 2
    It is dictionary generator expression.(dictionary comprehension) – Lab Jun 18 '20 at 14:27
  • So this iterates over the indices in `desired_order_list` and populates a new dictionary by looking up those indices in `sample_dict`. Read more on it here [dictionary comprehension](https://www.python.org/dev/peps/pep-0274/). Its basically a more compact way to populate a dict, rather than with a regular loop and updating with new key/vals – yatu Jun 18 '20 at 14:29
  • 1
    In addition, this reordering of the dict will only work in python3.7+, where dictionaries are sorted by insertion order – Manuel Jun 18 '20 at 14:31

0 Answers0