简体   繁体   中英

Shortcut to turn a ONE element dict into ONE tuple in Python

There are dozens of questions on turning a Python dict with some number of elements into a list of tuples. I am looking for a shortcut to turn a one element dict into a tuple.

Ideally, it would:

  1. Be idiomatic and simple (ie, not a subclass of dict , not a function, etc).
  2. Throw an error if there are more that one element in the dict.
  3. Support multiple assignment by tuple unpacking.
  4. Not destroy the dict .

I am looking for a shortcut to do this (that is not destructive to the dict):

k,v=unpack_this({'unknown_key':'some value'})

* does not work here.

I have come up with these that work:

k,v=next(iter(di.items()))   # have to call 'iter' since 'dict_items' is not

Or:

k,v=(next(((k,v) for k,v in di.items())))

Or even:

k,v=next(zip(di.keys(), di.values()))

Finally, the best I can come up with:

k,v=list(di.items())[0]      # probably the best...

Which can be wrapped into a function if I want a length check:

def f(di):
    if (len(di)==1): return list(di.items())[0]
    raise ValueError(f'Too many items to unpack. Expected 2, got {len(di)*2}')

These methods seem super clumsy and none throw an error if there is more than one element.

Is there an idiomatic shortcut that I am missing?

>>> d = {'a': 1}
>>> d.popitem()
('a', 1)

为什么不 :

next(iter(d.items())) if len(d)==1 else (None,None)

@chepner has the right approach with .popitem()<\/code> :

>>> d = {'a': 1}
>>> d.popitem()
('a', 1)        # d is now {}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM