简体   繁体   English

在Python中将有限的dict值解压缩为局部变量的优雅方法

[英]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.

相关问题 从 Python 中的局部变量创建 dict 的优雅方式 - Elegant way to create dict from local variables in Python 迭代字典 python 列表的优雅方式 - Elegant way of iterating list of dict python 在 Python 中将所有 dict 值与字符串载体作为单个字符串连接在一起的优雅方式 - Elegant way to concat all dict values together with a string carrier as a single string in Python 有没有一种优雅的方法可以同时在 python 中解压缩和索引关键字 arguments? - Is there an elegant way to simultaneously unpack and index key word arguments in python? python struct解压缩成dict - python struct unpack into a dict 在Python中通过引用修改变量列表的优雅方法? - Elegant way to modify a list of variables by reference in Python? 用python中的变量填充字典的一种优雅方法 - elegant way to fill dictionary with variables in python Python 元组到字典 - ValueError:要解压的值太多 - Python tuple to dict - ValueError: too many values to unpack 是否有一种优雅的方式组合 Python vars() 和 filter() 函数来显示变量子集的值? - Is there an elegant way of combining the Python vars() and filter() functions to display the values of a subset of variables? ValueError:当尝试在 python 中解压缩 dict 以使用 Pandas 进行数据标记时,没有足够的值来解压缩(预期为 2,得到 1) - ValueError: not enough values to unpack (expected 2, got 1) when trying to unpack dict in python for data labeling with pandas
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM