nedbat,
@nedbat@hachyderm.io avatar

A surprising way to get the item from a one-element dictionary:

tero,
@tero@masto.ai avatar

@nedbat You can make it not fail and just get the first item by unpacking the rest (using a throwaway name if you don’t need them).

[(k, v), *_] = d.items()

(Added in case someone who sees your post finds this useful)

minkiu,
@minkiu@mastodon.social avatar

@tero @nedbat i searched for this this past week, left me wondering if I should just use a tuple instead of dict, since I am the one generating the list of dicts to begin with 🤔

tero,
@tero@masto.ai avatar

@minkiu @nedbat Depends on your use case; if you don’t need to access an item by a key and don’t need mutability, I’d maybe go with tuples.

nedbat,
@nedbat@hachyderm.io avatar

@tero @minkiu It does sound like a tuple to begin with would be better in this case.

_KevinTrainor,
@_KevinTrainor@mastodon.online avatar

@nedbat When I look at this again, I realize that this all turns on the double square bracket syntax on the left side of the assignment. I am finding it hard to find a good resource that explains this syntax. Can anyone suggest one?

nedbat,
@nedbat@hachyderm.io avatar

@_KevinTrainor I'm not sure about a reference, but: python unpacks iterables on the right to match the iterable structure on the left.

It might help to experiment with statements like this:
[a, b, c] = [1, 2, 3]
[a, [b, c]] = [1, [2, 3]]
[[a, b]] = [[1, 2]]

Then remember that d.items() is an iterable, each element of which is an iterable pair.

_KevinTrainor,
@_KevinTrainor@mastodon.online avatar

@nedbat Wondering if this behavior is part of the specification or just an accident of implementation that might not persist over time…

nedbat,
@nedbat@hachyderm.io avatar

@_KevinTrainor This is definitely guaranteed behavior. What part of it seems accidental?

  • All
  • Subscribed
  • Moderated
  • Favorites
  • python
  • DreamBathrooms
  • mdbf
  • ngwrru68w68
  • magazineikmin
  • thenastyranch
  • rosin
  • khanakhh
  • osvaldo12
  • Youngstown
  • slotface
  • Durango
  • kavyap
  • InstantRegret
  • tacticalgear
  • anitta
  • ethstaker
  • provamag3
  • cisconetworking
  • tester
  • GTA5RPClips
  • cubers
  • everett
  • modclub
  • megavids
  • normalnudes
  • Leos
  • JUstTest
  • lostlight
  • All magazines