Roman
Roman

Reputation: 3241

Putting items into dictionary without changing order

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

The expected 'd' should be:

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

No problem if all values are tupled or listed.

Upvotes: 0

Views: 73

Answers (3)

aless80
aless80

Reputation: 3332

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

gives the following. Notice that 98 in 'Ant' is not "tupled" as asked in the original question.

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

Upvotes: 1

Bahrom
Bahrom

Reputation: 4862

Here's an approach using 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])])

Upvotes: 1

Eugene Yarmash
Eugene Yarmash

Reputation: 149776

Instead of replacing the value each time, add it to the tuple:

>>> 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,))])

BTW, since tuples are immutable, every append creates a new object. This would be more efficient if you use lists.

Upvotes: 5

Related Questions