0

I was looking at a python code which implemented topological sort and found the following code

data.update({item:set() for item in extra_items_in_deps})

I know what data.update does but am not sure how this:

item:set() for item in extra_items_in_deps  

works.

Mazdak
  • 105,000
  • 18
  • 159
  • 188
brokendreams
  • 827
  • 2
  • 10
  • 29

1 Answers1

3

This is a dictionary comprehension. It has the following syntax:

{ k: v for item in sequence }

This will create a dictionary entry for every item in sequence with the key k and the value v.

For example, the following will create a dictionary with the keys from the sequence (1, 2, 3), and the squared number as the value:

>>> { x: x**2 for x in (1, 2, 3) }
{1: 1, 2: 4, 3: 9}

In your case, you have the following dictionary comprehension:

{ item: set() for item in extra_items_in_deps }

This will create a dictionary with the keys from extra_items_in_deps and create a new set for each key. So assuming extra_items_in_deps = [1, 2, 3], it’s equivalent to this dictionary:

{ 1: set(), 2: set(), 3: set() }

This dictionary is then passed to data.update() which updates the dictionary data with the key-value pairs from the passed dictionary.

poke
  • 369,085
  • 72
  • 557
  • 602