I have this one line comprehension and am trying to break it down to understand it:
units = dict((s, [u for u in unitlist if s in u]) for s in boxes)
So far I have come up with this but it doesn't give the same output:
u = []
for s in boxes:
for u in unitlist:
if s in u:
u.append(u)
units = dict(u)
please advise, and also please guide me to any place i can understand how to switch between the two better. I find it easier to understand code without the one liners.
Original expression with list comprehension:
units = dict((s, [u for u in unitlist if s in u]) for s in boxes)
Classical reproduction:
units = {}
for s in boxes:
values = []
for u in unitlist:
if s in u:
values.append(u)
units[s] = values
Your original expression says "make a dict()
composed of key, value
pairs with s
as key
and a sublist of unitlist as value
"
Your expression also says there is a condition: although all s in boxes
will be found as keys in your units
dict, the associated values will be equal or a sublist of u
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With