0
\$\begingroup\$

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.

\$\endgroup\$

closed as off-topic by isaacg, PhiNotPi, Alex A., Downgoat, Peter Taylor Jul 23 '15 at 17:21

This question appears to be off-topic. The users who voted to close gave these specific reasons:

  • "This site is for programming contests and challenges. General programming questions are off-topic here. You may be able to get help on Stack Overflow." – Alex A., Downgoat, Peter Taylor
  • "Questions without an objective primary winning criterion are off-topic, as they make it impossible to indisputably decide which entry should win." – isaacg, PhiNotPi
If this question can be reworded to fit the rules in the help center, please edit the question.

  • 1
    \$\begingroup\$ Welcome to Programming Puzzles & Code Golf Stack Exchange! This site is for programming contests / challenges, not general programming questions. For those, try Stack Overflow, but be sure you read their help center first to make sure your question is of high quality and on-topic. \$\endgroup\$ – Martin Ender Jul 23 '15 at 19:51
1
\$\begingroup\$
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!

\$\endgroup\$
  • \$\begingroup\$ 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} \$\endgroup\$ – Kit Sunde Jul 23 '15 at 17:18

Not the answer you're looking for? Browse other questions tagged or ask your own question.