2013-04-11 79 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)