[英]Elegant way to unpack limited dict values into local variables in Python
I'm looking for an elegant way to extract some values from a Python dict into local values. 我正在寻找一种优雅的方法来从Python字典中提取一些值到本地值。
Something equivalent to this, but cleaner for a longer list of values, and for longer key/variable names: 与此相当的东西,但对于更长的值列表更清晰,以及更长的键/变量名称:
d = { 'foo': 1, 'bar': 2, 'extra': 3 }
foo, bar = d['foo'], d['bar']
I was originally hoping for something like the following: 我原本希望得到以下内容:
foo, bar = d.get_tuple('foo', 'bar')
I can easily write a function which isn't bad: 我可以轻松编写一个不错的函数:
def get_selected_values(d, *args):
return [d[arg] for arg in args]
foo, bar = get_selected_values(d, 'foo', 'bar')
But I keep having the sneaking suspicion that there is some other builtin way. 但我一直怀疑还有一些其他的内置方式。
You can do something like 你可以做点什么
foo, bar = map(d.get, ('foo', 'bar'))
or 要么
foo, bar = itemgetter('foo', 'bar')(d)
This may save some typing, but essentially is the same as what you are doing (which is a good thing). 这可以节省一些打字,但基本上和你正在做的一样(这是一件好事)。
Well, if you know the names ahead of time, you can just do as you suggest. 好吧,如果你提前知道这些名字,你可以按照你的建议去做。
If you don't know them ahead of time, then stick with using the dict - that's what they're for. 如果你没有提前知道它们,那么坚持使用dict - 这就是它们的用途。
If you insist, an alternative would be: 如果你坚持,另一种选择是:
varobj = object()
for k,v in d.iteritems(): setattr(varobj,k,v)
After which keys will be variables on varobj. 之后,键将是varobj上的变量。
Somewhat horrible, but: 有点可怕,但是:
globals().update((k, v) for k, v in d.iteritems() if k in ['foo', 'bar'])
Note, that while this is possible - it's something you don't really want to be doing as you'll be polluting a namespace that should just be left inside the dict
itself... 请注意,尽管这是可能的 - 这是你真的不想做的事情,因为你将污染一个应该只留在dict
本身内的命名空间......
If you're looking for elegance with performance across python versions, sadly I don't think you're gonna get any better than: 如果你在python版本中寻找优雅和性能,遗憾的是我认为你不会比以下更好:
unpack = lambda a,b,c,**kw: (a,b,c) # static
d = dict( a=1, b=2, c=3, d=4, e=5 )
a,b,c = unpack(**d)
The elegant solution: 优雅的解决方案:
d = { "foo": 123, "bar": 456, None: 789 }
foo, bar, baz = d.values() # 123, 456, 789
Notice that keys are not used, so be sure to get the order of your variables right, ie they must match the order that the keys were inserted into the map (this ordering is guaranteed since Python 3.6). 请注意,未使用键,因此请务必正确获取变量的顺序,即它们必须与键插入映射的顺序相匹配(自Python 3.6起,此顺序保证)。 If in doubt about ordering, use the other methods. 如果对订购有疑问,请使用其他方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.