我的字典包含我在函数中需要的值。
目前,我逐个提取值并将它们存储在局部变量中以便进一步处理。像这样:
def func(the_dict):
a=the_dict['a']
b=the_dict['b']
b=the_dict['c']
问题是它有点冗长,有没有办法以更简洁的方式提取变量?
答案 0 :(得分:3)
您可以使用map并解压缩:
a, b, c = map(the_dict.get,("a","b","c"))
print(a,b,c)
答案 1 :(得分:2)
您可以使用operator.itemgetter
一次获取多个值:
>>> from operator import itemgetter
>>> the_dict = {'a':1, 'b':2, 'c':3}
>>> a, b, c = itemgetter('a', 'b', 'c')(the_dict)
>>> a
1
>>> b
2
>>> c
3