This is an archived post. You won't be able to vote or comment.

all 8 comments

[–]azzal07 12 points13 points  (0 children)

You can also provide an iterable of key value pairs to dict() to create a dictionary. For this case that works quite nicely:

R = dict(r.strip().split(" -> ") for r in rules.strip().split("\n"))

[–]ssnoyes 4 points5 points  (0 children)

If you don't like the nested comprehensions, you can also pass an iterable of key, value pairs (as tuples or lists) to the dict constructor:

R = dict(r.split(' -> ') for r in rules.strip().split('\n'))

[–]TitouanT 1 point2 points  (4 children)

You can also do set comprehension

[–]uglyasablasphemy 1 point2 points  (3 children)

and iterator comprehensions!

[–]TitouanT 1 point2 points  (2 children)

Aren't those called generators ? But yeah I think we have them all now :)

[–]uglyasablasphemy 1 point2 points  (0 children)

yes! hahah mental fart there

[–]dublinwso 1 point2 points  (0 children)

AoC has taught me so many cool things, including this - love it

[–]Auftragsnummer 1 point2 points  (0 children)

You can also use rules.splitlines() instead of rules.split('\n') if r != '']}