Firstly, lets decompose your example:
item_init = ((i.tag, (type(i.text) == str and i.text.strip() or i.text)) for i in r if i.tag != "tid_item")
item = dict(item_init)
Now, if you look at the definition of the type dict
in python (help(dict)
), you will see that a dict object can be initialized with an iterable
of (key, value) pairs. The item_init
variable contains a generator and yield an iterable of tuples.
Next, look at the expression (i.tag, (type(i.text) == str and i.text.strip() or i.text))
. You may not understand the second part of the expression because it looks like a boolean operation but is actually a conditionnal assignment operation which means:
if type(i.text)
is str
then assign i.text.strip()
else, assign i.text
Finally, the item_init
object is a generator of 2-uples where, for each element of r, the first part is the tag and the second is the text (stripped, if necessary). The tag will be used as keys and the text as values in the final dict object.