2016-03-28 44 views
0
from collections import OrderedDict 

l = [('Monkey', 71), ('Monkey', 78), ('Ostrich', 80), ('Ostrich', 96), ('Ant', 98)] 

d = OrderedDict() 
for i, j in l: 
    d[i] = j 
print d 
OrderedDict([('Monkey', 78), ('Ostrich', 96), ('Ant', 98)]) 

预期“d”应该是:把物品放入字典不改变为了

OrderedDict([('Monkey', (71,78)), ('Ostrich', (80,96)), ('Ant', 98)]) 

如果所有值都tupled或上市没有问题。

+3

为什么这是预期的输出?每个键只能有一个值,此时您将*替换上一个值。 – jonrsharpe

+0

是的预期输出应该包括所有相应的值,但不知道如何去做。 – jean

+3

你需要仔细检查你的代码,并理解'd [i] = j'实际上在你的代码中做了什么。看看你期待的数据结构。看看你在做什么。确定如何在更新字典中的值的上下文中正确创建该数据结构。使用文档卢克。 – idjaw

回答

5

不是每次都来取代值,将其添加到元组:

>>> l = [('Monkey', 71), ('Monkey', 78), ('Ostrich', 80), ('Ostrich', 96), ('Ant', 98)] 
>>> d = OrderedDict() 
>>> for i, j in l: 
...  if i in d: 
...   d[i] += (j,) 
...  else: 
...   d[i] = (j,) 
... 
>>> d 
OrderedDict([('Monkey', (71, 78)), ('Ostrich', (80, 96)), ('Ant', (98,))]) 

顺便说一句,因为tuple s为不可变的,每次追加创建一个新对象。如果您使用list s,这将更有效率。

+0

是的列表也可以。 – jean

+0

如何做列表? – jean

+1

@jean:'for i,j in l:d.setdefault(i,[])。append(j)' – GingerPlusPlus

1

下面是一个使用groupby的方法:

from itertools import groupby 

l = [('Monkey', 71), ('Monkey', 78), ('Ostrich', 80), ('Ostrich', 96), ('Ant', 98)] 
       # Key is the animal, value is a list of the available integers obtained by 
d = OrderedDict((animal, [i for _, i in vals]) 
       for (animal, vals) in 
       # Grouping your list by the first value inside animalAndInt, which is the animal 
       groupby(l, lambda animalAndInt: animalAndInt[0])) 
# If you want a tuple, instead of [i for _, i in vals] use tuple(i for _, i in vals) 
print(d) 
>>> OrderedDict([('Monkey', [71, 78]), ('Ostrich', [80, 96]), ('Ant', [98])]) 
1
for i, j in l: 
    if i in d: 
     #d[i] = (lambda x: x if type(x) is tuple else (x,))(d[i]) 
     #Eugene's version: 
     if not isinstance(d[i], tuple): 
      d[i] = (d[i],) 
     d[i] += (j,) 
    else: 
     d[i] = j 

给出以下。请注意,'Ant'中的98不像原始问题中提到的那样是“tupled”。

OrderedDict([('Monkey', (71, 78)), ('Ostrich', (80, 96)), ('Ant', 98)]) 
+0

如果是tupled或列出。 – jean

+0

如果不是isinstance(d [i],tuple),那么这将会更加可读,而不是使用'lambda':'d [i] =(d [i],)' –

+0

谢谢,我编辑我的回复 – aless80