2013-04-11 76 views
0

如何从匿名字典中获取任意值的元组?如何从字典中获取任意值的元组?

def func(): 
    return dict(one=1, two=2, three=3) 

# How can the following 2 lines be rewritten as a single line, 
# eliminating the dict_ variable? 
dict_ = func() 
(one, three) = (dict_['one'], dict_['three']) 

回答

1

Loop over the func() result?

one, three = [v for k, v in sorted(func().iteritems()) if k in {'one', 'three'}] 

如果你使用Python 3.更换.iteritems().items()

演示:

>>> def func(): 
...  return dict(one=1, two=2, three=3) 
... 
>>> one, three = [v for k,v in sorted(func().iteritems()) if k in {'one', 'three'}] 
>>> one, three 
(1, 3) 

注意,这种方法需要你保持你的目标名单中排序键顺序,而是一个陌生限制某些应该简单明了的事情。

这是更为详细比你的版本。真的,没有什么不对。

+0

失败,看看你的演示结果 - FUNC()[ '一'] = 3 – ch3ka 2013-04-11 14:57:21

+0

@ ch3ka:固定;!它需要一个排序。 – 2013-04-11 14:59:10

+0

仍然无法在一般的情况下 – ch3ka 2013-04-11 14:59:40

2

有什么不对的中间变量?老实说,这是WAY比这个丑陋的东西我熟起来,以摆脱它更好地:

>>> (one,three) = (lambda d:(d['one'],d['three']))(func()) 

(这确实没有什么比使中间值成是动态生成的函数等)

+0

同意;我的和你的都比必要的更丑陋。 – 2013-04-11 14:59:39

+0

谢谢。请注意,我并没有要求优先选择的方式,只是为了可能的选择。只有这样我才能做出风格选择。迄今为止,我同意中间变量比所提供的3种替代方案更清晰。到目前为止的3种选择中,我最喜欢你的。 – 2013-04-11 18:25:48

1

不要那样做,中间字典是在大多数情况下的罚款。可读性计数为 。 如果你真的发现自己过于频繁在这种情况下,你可以使用一个装饰器猴补丁的功能:

In  : from functools import wraps 

In  : def dictgetter(func, *keys): 
    .....:  @wraps(func) 
    .....:  def wrapper(*args, **kwargs): 
    .....:   tmp = func(*args, **kwargs) 
    .....:   return [tmp[key] for key in keys] 
    .....:  return wrapper 

In  : def func(): 
    ....:   return dict(one=1, two=2, three=3) 
    ....: 

In  : func2 = dictgetter(func, 'one', 'three') 

In  : one, three = func2() 

In  : one 
Out : 1 

In  : three 
Out : 3 

或类似的东西。

当然,你也可以猴补丁,让您在calltime指定所需的字段,但你会希望它包装这些机制的普通函数,我猜。

这将可以实现非常相似,高清包装的身体上面,像

one, three = getfromdict(func(), 'one', 'three') 

或类似的东西使用,但你也可以重新使用上述整体装饰:

In  : two, three = dictgetter(func, 'two', 'three')() 

In  : two, three 
Out : (2, 3)