我一直在寻找一种以通用方式“解包”字典的方法,并找到了解释各种技术的a relevant question(和答案)(TL; DR:它不太优雅)。
然而,该问题解决了dict的密钥未知的情况,OP会将它们自动添加到本地名称空间。
我的问题可能更简单:我从一个函数中得到一个dict,并希望在运行时解析它,知道我需要的密钥(我可能不需要每次都使用它们)。现在我只能做
def myfunc():
return {'a': 1, 'b': 2, 'c': 3}
x = myfunc()
a = x['a']
my_b_so_that_the_name_differs_from_the_key = x['b']
# I do not need c this time
当我在寻找相当于
的时候def myotherfunc():
return 1, 2
a, b = myotherfunc()
但是对于一个dict(这是我的函数返回的)。我不想使用后一种解决方案有几个原因,其中一个原因是哪个变量对应哪个返回元素并不明显(第一个解决方案至少具有可读性的优点)。
此类操作是否可用?
答案 0 :(得分:2)
如果你真的必须,你可以使用operator.itemgetter()
object提取多个键的值作为元组:
from operator import itemgetter
a, b = itemgetter('a', 'b')(myfunc())
这仍然不漂亮;我更喜欢显式和可读单独的行,您首先分配返回值,然后提取这些值。
演示:
>>> from operator import itemgetter
>>> def myfunc():
... return {'a': 1, 'b': 2, 'c': 3}
...
>>> itemgetter('a', 'b')(myfunc())
(1, 2)
>>> a, b = itemgetter('a', 'b')(myfunc())
>>> a
1
>>> b
2
答案 1 :(得分:2)
你也可以使用map:
def myfunc():
return {'a': 1, 'b': 2, 'c': 3}
a,b = map(myfunc().get,["a","b"])
print(a,b)
答案 2 :(得分:0)
除operator.itemgetter()
方法外,您还可以编写自己的myotherfunc()
。它将所需键的列表作为参数,并返回其对应值的元组。
def myotherfunc(keys_list):
reference_dict = myfunc()
return tuple(reference_dict[key] for key in keys_list)
>>> a,b = myotherfunc(['a','b'])
>>> a
1
>>> b
2
>>> a,c = myotherfunc(['a','c'])
>>> a
1
>>> c
3