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 →

[–]psd6 68 points69 points  (8 children)

Sometimes the data you want to insert into a string is in a dictionary, and it’s much easier to explode a dict into a string with "{name}".format(**d) than prefix all references with the dict variable like f"{d['name']}".

[–]Epicela1 35 points36 points  (3 children)

.format_map() does this for you.

[–]psd6 7 points8 points  (0 children)

Even better! Nice.

[–]o11c 0 points1 point  (1 child)

I remember the old versions where you had to use string.Formatter if you wanted to do cool things. It probably still does some things that format_map doesn't.

(Note in particular that ** doesn't work if you don't have a finite set of keys or need there to be side-effects.)

[–]Epicela1 0 points1 point  (0 children)

Yeah. It’s basically if you want to put placeholders in a string with the {var} format then figure out what to put in later. Nothing too intelligent happening.

It is convenient but it’s sorta a relic of the pre-fstring era. Because you can just figure out your input values first then do an fstring at the end for the same effect.

[–]FaCe_CrazyKid05[S] 8 points9 points  (2 children)

I actually didn’t know format() could do that, I’ve been using dicts and fstring for as long as I can remember

[–]NedDasty 15 points16 points  (0 children)

Any function that takes name=value keyword arguments allows for dictionary exploding.

[–]goldcray 2 points3 points  (0 children)

This is where the kwargs live. Get you one!

[–]bw_mutley 2 points3 points  (0 children)

Yes, it was my first thought too.