2015-07-11 44 views
1

我正在寻找一种以通用方式“解压缩”字典的方法,并找到解释各种技术(TL; DR:它不太优雅)的a relevant question(和答案)。是否可以在一次调用中“解开”一个字典?

但是,这个问题解决了字典中的键未知的情况,OP将它们自动添加到本地名称空间中。

我的问题可能更简单:我从一个函数中获得一个字典,并且想知道我需要的密钥(我可能不需要每次都需要它们)。现在我只能做

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() 

相当于而是一个字典(这是由我的函数返回)。我不想使用后一种解决方案,其中一个原因是,哪个变量对应哪个返回元素(第一个解决方案至少具有可读性的优点)并不明显。

这样的操作是否可用?

+0

'A,B = FOO()得到( 'A'),富()得到( 'B')'我想可以工作。以通常的方式拆封它的问题是无序的字迹。 – IanAuld

+0

谢谢,但我不想调用该函数两次(或更多),否则我会去我的问题中提到的(第一)解决方案。 – WoJ

回答

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 
2

您还可以使用地图:

def myfunc(): 
    return {'a': 1, 'b': 2, 'c': 3} 

a,b = map(myfunc().get,["a","b"]) 
print(a,b) 
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 
相关问题