简体   繁体   中英

how does “x:set() for x in y” work?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM