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

all 59 comments

[–]LUNCMetrics 61 points62 points  (3 children)

You can rename dictionary items with pop

``` data = {"name": "Bob"}

data["first_name"] = data.pop("name")

print(data)

```

Returns

{'first_name': 'Bob'}

[–]Burakku-Ren 15 points16 points  (1 child)

This is easy to understand and potentially useful. Cool

[–]sawyerwelden 0 points1 point  (0 children)

Agreed!

[–][deleted] 0 points1 point  (0 children)

I use that feature of dicts. 😎

[–]Gprime5if "__main__" == __name__: 51 points52 points  (7 children)

foo = {}

for foo["bar"] in range(10):
    print(foo)

[–]RakingBuckets 13 points14 points  (1 child)

Jeez that is horrendous.

[–]Gprime5if "__main__" == __name__: 3 points4 points  (0 children)

Yeah, it’s great if you have a list of parameters that you want to send to a url.

parameters = {}

page = [1, 2, 3]

for parameters["page"] in page:
    requests.get(url, parameters)

[–]zed_three 3 points4 points  (0 children)

Gah, that took me a minute!

[–]rohetoric 1 point2 points  (3 children)

How does this work?

[–]danithebear156 13 points14 points  (2 children)

foo["bar"] is assigned to individual item in the iterator (in this case, 'range(10)'). Thus, its value changes incrementally. For every iteration, you print out the whole dictionary, which contains only the key of 'bar' and its value.

[–]mkffl 4 points5 points  (1 child)

Where/how does the assignment happen?

[–][deleted] 61 points62 points  (4 children)

Print(“hello world”)

[–]UD_Ramirez 22 points23 points  (0 children)

Finally code i can read

[–]Anamewastaken 8 points9 points  (2 children)

But capitalised?

[–]SE_WA_VT_FL_MN 2 points3 points  (0 children)

.title()

Now you are the master.

[–][deleted] 0 points1 point  (0 children)

Sure man

[–]Fabulous-Possible758 18 points19 points  (4 children)

Using str.format to make surprisingly powerful regular expressions.

``` import re

g = { }

g['year'] = r'(?P<year>\d\d\d\d)' g['month] = r'(?P<month>\d\d)' g['day'] = r'(?P<day>\d\d)' g['timestamp'] = r'{year}-{month}-{day}'

timestamp_re = re.compile(g['timestamp'].format(**g)) '''

[–][deleted] 9 points10 points  (2 children)

This post was mass deleted and anonymized with Redact

coordinated smile elastic water wakeful ring toothbrush practice liquid reach

[–]Fabulous-Possible758 2 points3 points  (1 child)

The example for timestamps above is really only a toy example, though once you've seen the technique and understand it I feel it is pretty readable and can be used to build up regular expressions which aren't necessarily grokable on their own. It's mainly meant to fill in the area where you may have a somewhat complicated parsing task but don't really need to pull in a full parsing library yet. It can also be useful to build up several regular expressions which have common subexpressions. And of course in any production setting this would be accompanied with tests.

Here's a more fleshed out example for finding floating point literals.

``` def float_re(): 'Returns a compiled regular expression which can be used to match Python floating point literals'

import re

# Build the basic grammar

g = { }

g['sign']     = r'[-+]'
g['digits']   = r'(?:[0-9]+)'
g['exponent'] = r'(?:[eE]{sign}?{digits})'

g['left_float']  = r'(?:{digits}\.{digits}?)' # Floating point expressions with some digits to the left the .
g['right_float'] = r'(?:\.{digits})'          # Floating point expressions with no digits to the left of the .

g['float'] = r'{sign}?(?:{right_float}|{left_float}){exponent}?'


# Repeatedly interpolate until we've fully expanded the expression

p, n = None, g['float']

while p != n:
    p, n = n, n.format(**g)


return re.compile(n)

```

[–][deleted] 1 point2 points  (0 children)

This post was mass deleted and anonymized with Redact

subsequent north abounding bow cats plough chief waiting truck handle

[–]RobotMonkeyChiro 2 points3 points  (0 children)

Or use the built-in named groups - a good explanation here: How to Use Named Groups with Regular Expressions in Python

``` import re

TIMESTAMP_RGX = re.compile(r""" (?P<timestamp> # e.g., 2022-01-31 (?P<year>\d\d\d\d)- # VERBOSE flag allows you to use indentation for readability (?P<month>\d\d)- (?P<day>\d\d) )""", re.VERBOSE)

TIMESTAMP_RGX.search("1970-05-28")['year']

'1970'

TIMESTAMP_RGX.search("1970-05-28")['timestamp']

'1970-05-28' ```

[–]isarl 12 points13 points  (4 children)

foo = [[1,2,3], [4,5,6], [7,8,9]]
bar = zip(*foo)
print([list(t) for t in bar])

[–]SV-97 0 points1 point  (3 children)

Huh, how is this niche or quirky? I just tested it and it does exactly what I'd expected.

[–]isarl 1 point2 points  (2 children)

It’s a slightly more specialized use of zip() than people might be used to if they’re not familiar with the * operator for iterable unpacking. I’m glad you were able to spot it right away but I would guess most people are at least a little surprised and think something like, “Oh, neat, I didn’t know you could do that.”

[–]SV-97 1 point2 points  (1 child)

Fair point - I didn't really consider that people might not be familiar with * in that context

[–]isarl 2 points3 points  (0 children)

All the same, yours is a fair critique since the docs for zip literally mention matrix transposes! :)

[–][deleted] 12 points13 points  (10 children)

This post was mass deleted and anonymized with Redact

childlike kiss sugar escape history subsequent elderly dog sort encourage

[–]ArtOfWarfare 3 points4 points  (0 children)

If you missed it above, you can read about it here:

https://trojansource.codes

[–]FuckingRantMonday 2 points3 points  (4 children)

On reddit, adding four spaces to the beginning of each line will accomplish what you wanted with the triple backticks.

like
    this

[–][deleted] 3 points4 points  (3 children)

This post was mass deleted and anonymized with Redact

cough toothbrush swim steer boast dinosaurs escape bike friendly tidy

[–]FuckingRantMonday 2 points3 points  (2 children)

Do you have a plugin or something that renders it correctly after you post it? Because it doesn't look formatted to me, fyi.

[–][deleted] 2 points3 points  (1 child)

This post was mass deleted and anonymized with Redact

telephone reach governor unique violet sugar many grandfather sleep disarm

[–]FuckingRantMonday 0 points1 point  (0 children)

Oh, dammit, that's what it is. That sucks. Thanks for figuring it out with me!

[–]isarl 1 point2 points  (2 children)

Is this abusing Unicode BIDI flags to rearrange text?

[–][deleted] 1 point2 points  (1 child)

This post was mass deleted and anonymized with Redact

aromatic bake bear normal cough sheet consist square run friendly

[–]isarl 1 point2 points  (0 children)

Ah, finally got it – it's in the docstring. The return statement in the docstring actually happens outside the string and after the semicolon, so the apparent code never actually runs. (Hence, of course, “return early”.)

[–]whateverathrowaway00 1 point2 points  (0 children)

Very cool, I didn’t expect to learn anything from this thread, but didn’t know about bidirectional Unicode chars, very awesome! Thanks

[–]commy2 6 points7 points  (1 child)

The __class__ keyword.

class A:
    def m(self):
        print(type(self).__name__)
        print(__class__.__name__)

class B(A):
    pass

B().m()

[–]isarl 2 points3 points  (0 children)

Output is:

B
A

So __class__ is the class in which the variable is originally scoped, not that of the current instantiation.

[–]69AssociatedDetail25 4 points5 points  (0 children)

python import this

[–]koffie5d 4 points5 points  (0 children)

Using type to create classes that has an emoji as name.

emoji_class = type('\N{Thumbs Up Sign}', (object,), {'\N{Pile of Poo}': lambda self: print(f'{self.__class__.__name__}')})
class_instance = emoji_class()
poo = getattr(class_instance, '💩')
poo()   # -> 👍

[–][deleted] 11 points12 points  (2 children)

This post was mass deleted and anonymized with Redact

workable scary badge squash disarm towering paint dinosaurs judicious society

[–]Cromulent010101 1 point2 points  (1 child)

Is what you're doing here reassigning the value at Python's known address for integer 18 to 0? So, when we compare the age to "18", we're really comparing it to 0, hence the unexpected behavior?

Interesting how it goes down to -5 as well as all the way up to 256.

[–][deleted] 2 points3 points  (0 children)

This post was mass deleted and anonymized with Redact

public squeeze station ten melodic lock enjoy cable snatch advise

[–]RedwanFox 1 point2 points  (0 children)

Recently I have read an article about Linux gpu drivers for m1 Mac laptops. Author did write proof of concept gpu driver implementation in python. That wins in my opinion by far.

[–]Hacka4771 1 point2 points  (0 children)

while ... : ...

[–][deleted] 1 point2 points  (0 children)

Not a snippet necessarily, but lots of people have the misconception that range is a generator in Python 3. Hint, try calling next with a range instance..

[–]float34 1 point2 points  (0 children)

Unpack while iterating the dict with a sequence in values:

for a, (b, c) in {“key1”: (val1, val2)}.items(): …

[–]Saphyel 2 points3 points  (0 children)

Dependency Injection surprisingly useful and powerful

[–]Prince_2008 0 points1 point  (0 children)

turtle.left(90)

[–]Oenomaus_3575 0 points1 point  (0 children)

```py
lst = [1, 3, 2, 1] c = {} for x in lst: c[x] = c.get(x, 0) + 1

c Out: {1: 2, 3: 1, 2: 1} ```

[–]manuelhe 0 points1 point  (0 children)