Merging a dict compression referencing the original list into 1 line

0

Background

A question wanted to solve a problem in a way that made it unreasonably complex: https://stackoverflow.com/a/31551257/29347

The problem in the original question is:

Take a list of (key, value) and produce a dict such that {key: sum(value)}

My Problem

I want to use dict compression with list.count or str.count but constructing the iterable, iterating and referencing it in one motion has me stumped.

a = [("a",1), ("b",3), ("a",5)]

# b = "abbbaaaaa"
b = "".join(b[0] * b[1] for b in a)

# dict_a = {'a': 6, 'b': 3}
dict_a = {e[0]: b.count(e) for e in b}

Goal

Remove the need for the variable b thus merging the two lines whilst staying true to the solution.

Kit Sunde

Posted 2015-07-23T16:58:46.867

Reputation: 117

Question was closed 2015-07-23T17:21:36.473

1

Welcome to Programming Puzzles & Code Golf Stack Exchange! This site is for programming contests / challenges, not general programming questions. For those, try [so], but be sure you read their help center first to make sure your question is of high quality and on-topic.

– Martin Ender – 2015-07-23T19:51:30.597

Answers

1

dict_a = {t[0] : sum(tp[1] for tp in a if tp[0] == t[0]) for t in a}

Horribly slow, but hey it's a one liner!

Dleep

Posted 2015-07-23T16:58:46.867

Reputation: 111

Haha I literally just updated my original example with the almost identical: dict_a = {e[0]: sum(map(itemgetter(1), filter(lambda a: a[0] == e[0], a))) for e in a} – Kit Sunde – 2015-07-23T17:18:29.107