简体   繁体   English

"在 Python 中将 ONE 元素字典转换为 ONE 元组的快捷方式"

[英]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.将具有一定数量元素的 Python dict 转换为元组列表有很多问题。 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).惯用且简单(即,不是dict的子类,不是函数等)。
  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 .不破坏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> : @chepner 对.popitem()<\/code>有正确的方法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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