2

I got a list which is built up like this:

item_list = [
    [ObjectB, 9],
    [ObjectA, 2],
    [ObjectB, 5],
    [ObjectC, 8],
    [ObjectA, 7]
]

As you can see ObjectA and ObjectB are two times in this list. The left column defines which kind of item it is, the right how often I need it. Therefore I'd like to get a result like this:

item_list = [
    [ObjectB, 14],
    [ObjectA, 9],
    [ObjectC, 8],
]

[ObjectB, 9] and [ObjectB, 5] got merged together to [ObjectB, 14] and so did the ObjectA occurrences. What is the best way to achieve this? I tried several solutions but I feel like there's an really easy and efficient one.

1
  • 2
    Try converting it into a dictionary Commented Aug 10, 2015 at 13:48

2 Answers 2

8

Obviously, a dictionary will come handy for your problem:

d = defaultdict(int)
for k, v in item_list:  # unwrapping credits to @clemtoy
    d[k] += v
result = [[k, v] for k, v in d.iteritems()]

So what you do first is create a defaultdict, using int as a factory method. This means that if you try to access any key in the dictionary that does not exist, you will get 0.

Next you start filling your dictionary, by incrementing the values for the keys. If the key is not yet in the dictionary, you will, start from 0.

Now finally to transform back to the structure you want, you need the last line - list comprehension. And your result will be:

[[ObjectA, 9], [ObjectB, 14], [ObjectC, 8]]

Moreover, if you need it sorted, go ahead:

result = sorted(result, key=itemgetter(1), reverse=True)))

This will sort your result in descending order, using the second subelement of each element.

Sign up to request clarification or add additional context in comments.

2 Comments

Nice! But for k, v in item_list: d[k] += v would be the cutest in my view!
Worked out perfectly! Thanks!
1

Like this?

ObjectA = "hello"
ObjectB = "cruel"
ObjectC = "world"

item_list = [
    [ObjectB, 9],
    [ObjectA, 2],
    [ObjectB, 5],
    [ObjectC, 8],
    [ObjectA, 7]
]

sum = {}
for item in item_list:
    sum[item[0]] = sum.get(item[0], 0) + item[1]
print(sum)

{'world': 8, 'cruel': 14, 'hello': 9}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.