2013-04-29 64 views
2

鑑於這種元組:快譯通理解問題

my_tuple = ('chess', ['650', u'John - Tom']) 

我要創建字典,其中chess是關鍵。它應該導致:

my_dict = {'chess': ['650', u'John - Tom']} 

我有這樣的代碼

my_dict = {key: value for (key, value) in zip(my_tuple[0], my_tuple[1])} 

但它是有缺陷的,結果:

{'c': '650', 'h': u'John - Tom'} 

能否請你幫我修復它?

回答

2
>>> my_tuple = ('a', [1, 2], 'b', [3, 4]) 
>>> dict(zip(*[iter(my_tuple)]*2)) 
{'a': [1, 2], 'b': [3, 4]} 

因爲雖然你的具體情況:

{my_tuple[0]: my_tuple[1]} 
+0

+1,這是最好的靈活的解決方案,儘管我仍然不確定OP是否需要它。 – 2013-04-29 11:10:15

+0

@Lattyware我在OP的特定情況下添加了一個註釋 – jamylak 2013-04-29 11:10:44

3

這樣的事情,如果你的元組喜歡的樣子:(key1,value1,key2,value2,...)

In [25]: dict((my_tuple[i],my_tuple[i+1]) for i in xrange(0,len(my_tuple),2)) 
Out[25]: {'chess': ['650', 'John - Tom']} 

使用字典-理解:

In [26]: {my_tuple[i]: my_tuple[i+1] for i in xrange(0,len(my_tuple),2)} 
Out[26]: {'chess': ['650', 'John - Tom']} 

如果物品的數量在元組是沒有那麼大:

In [27]: { k : v for k,v in zip(my_tuple[::2],my_tuple[1::2])} 
Out[27]: {'chess': ['650', 'John - Tom']} 

使用迭代器:

In [36]: it=iter(my_tuple) 

In [37]: dict((next(it),next(it)) for _ in xrange(len(my_tuple)/2)) 
Out[37]: {'chess': ['650', 'John - Tom']} 
+1

+1但是你可以使用2.7語法,因爲OP聲明瞭2.7 – jamylak 2013-04-29 11:06:05

+0

我真的不明白OP的問題是如何需要的 - 據我所知,OP不是在討論比兩個值更長的元組。通過索引迭代也是一種不好的方法,相反,我會使用['itertools''' grouper()'recipe](http://docs.python.org/3.3/library/itertools.html#itertools - 食譜)。 – 2013-04-29 11:09:25

+0

@Lattyware這個方法對於OP的需求是很好的,只要他不使用生成器,並且它確實說*元組*它應該是好的 – jamylak 2013-04-29 11:13:46

4

你總是可以創建一個字典從元組與2個值的列表,(或單個元組)。

像這樣:

>>> my_tuple = ('chess', ['650', u'John - Tom']) 
>>> d = dict([my_tuple]) 
>>> d 
{'chess': ['650', u'John - Tom']} 

在這個簡單的方法,你也可以有一個元組列表...

>>> my_tuple_list = [('a','1'), ('b','2')] 
>>> d = dict(my_tuple_list) 
>>> d 
{'a': '1', 'b': '2'} 
+0

但OP沒有元組列表 – jamylak 2013-04-29 11:15:50

+0

@jamylak你是對的,這就是爲什麼它在我的答案的次要部分。第一部分簡單地解釋了在兩種情況下都可以使用相同的「方法」,這很簡單。 (你的文章還提出了一個更強大的解決方案,爲什麼你批評我的答案?) – 2013-04-29 11:22:54

+0

我不是在批評你的答案,它確實可以讓你對洞察'dict'構造函數有所瞭解。我只是說OP沒有這個數據結構 – jamylak 2013-04-29 11:29:47

3
>>> my_tuple = ('chess', ['650', u'John - Tom']) 
>>> it = iter(my_tuple) 
>>> {k: next(it) for k in it} 
{'chess': ['650', u'John - Tom']} 

>>> my_tuple = ('a', [1, 2], 'b', [3, 4]) 
>>> it = iter(my_tuple) 
>>> {k: next(it) for k in it} 
{'a': [1, 2], 'b': [3, 4]}