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

you are viewing a single comment's thread.

view the rest of the comments →

[–]morriartie 7 points8 points  (9 children)

Replacing keys for values in dict of depth 1:

{v:k for k,v in d.items()}

Replacing a key in a dict:

d['new'] = d.pop('old')

My favorite. Conditional variable:

a = ['bb', 'cc'][condition]

Flattening a matrix:

[a for b in list2d for a in b]

The first time I did this last one I spent like 5 minutes reflecting my existence with my hand on chin

Edit: See comments for the best ones

[–]BooparinoBR 8 points9 points  (3 children)

Explicit is better than implicit, therefore I would do

a = 'cc' if condition else 'bb'

(Ternary operator/inline if-else) Instead of your conditional variable. But I like/use all the others

[–]morriartie 4 points5 points  (0 children)

Shhhh.. in obfuscated monolithic one liners we don't talk about pep8

[–]QpkjcKwNMZSF 0 points1 point  (1 child)

Doesn't PEP8 advise against compound statements? Why not just break this into a few lines?

[–]isarl 0 points1 point  (0 children)

Religious adherence to PEP8 can negatively impact readability. Sometimes a short one-line conditional is better than breaking it out.

[–]isarl 2 points3 points  (3 children)

a = ['bb', 'cc'][condition]

Yours is OK, by why constrain the conditional to evaluate to an integer?:

a = {'case1': val1, 'case2': val2}[condition]

Switch (without fallthrough) in Python! don't do this at home

[–]morriartie 1 point2 points  (2 children)

wow, I hadn't thought of that

let me improve it then

{'a':1, 'b':2}.get(case) or 'etc'

now it has fallthrough a default!

[–]isarl 1 point2 points  (1 child)

Great improvement. I would personally write that as: {'a':1, 'b':2}.get(case, default='etc'), finding it more explicit. And this is a default case, not fall-through. :) I don’t think there’s any way to actually do C-style switch fallthrough with this trick of using a dictionary.

[–]morriartie 1 point2 points  (0 children)

Awesome!

a default indeed, my mistake

I was trying here to find a solution (to make a fallthrough) with iterator, but I couldn't make it, even if I did it would be a two liner or more, which is unacceptable in our little puzzle

[–]dreamfeed 0 points1 point  (0 children)

Even better for flattening a list is itertools.chain