[英]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:理想情况下,它将:
dict
, not a function, etc).dict
的子类,不是函数等)。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.