Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7495039
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 29, 20262026-05-29T17:58:28+00:00 2026-05-29T17:58:28+00:00

A generator expression is throwing off a large number of tuple pairs eg. in

  • 0

A generator expression is throwing off a large number of tuple pairs eg. in list form:

pairs = [(3, 47), (6, 47), (9, 47), (6, 27), (11, 27), (23, 27), (41, 27), (4, 67), (9, 67), (11, 67), (33, 67)]

For each pair in pairs, with key = pair[0] and value = pair[1], I want to feed this stream of pairs into a dictionary to cumulatively add the values for the respective keys. The obvious solution is:

dict_k_v = {}
for pair in pairs:
    try:
        dict_k_v[pair[0]] += pair[1]
    except:
        dict_k_v[pair[0]] = pair[1]

>>> dict_k_v
{33: 67, 3: 47, 4: 67, 6: 74, 9: 114, 11: 94, 41: 27, 23: 27}

However, could this be achieved with a generator expression or some similar construct that doesn’t use a for-loop?

EDIT

To clarify, the generator expression is throwing off a large number of tuple pairs:

(3, 47), (6, 47), (9, 47), (6, 27), (11, 27), (23, 27), (41, 27), (4, 67), (9, 67), (11, 67), (33, 67) …

and I want to accumulate each key-value pair into a dictionary (see Paul McGuire’s answer) as each pair is being generated. The pairs = list[] statement was unnecessary and sorry about that. For each pair (x,y), x is an integer and y can be an integer or decimal/float.

My generator expression is of the form:

((x,y) for y in something() for x in somethingelse())

and want to accumulate each (x,y) pair into a defaultdict. Hth.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-29T17:58:29+00:00Added an answer on May 29, 2026 at 5:58 pm

    For discussion, here is a simple generator function to give us some data:

    from random import randint
    def generator1():
        for i in range(10000):
            yield (randint(1,10), randint(1,100))
    

    And here is the basic solution that uses a Python for-loop to consume the generator and tally up counts for each key-value pair

    from collections import defaultdict
    
    tally = defaultdict(int)
    for k,v in generator1():
        tally[k] += v
    
    for k in sorted(tally):
        print k, tally[k]
    

    Will print something like:

    1 49030
    2 51963
    3 51396
    4 49292
    5 51908
    6 49481
    7 49645
    8 49149
    9 48523
    10 50722
    

    But we can create a coroutine that will accept each key-value pair sent to it, and accumulate them all into a defaultdict passed into it:

    # define coroutine to update defaultdict for every
    # key,value pair sent to it
    def tallyAccumulator(t):
        try:
            while True:
                k,v = (yield)
                t[k] += v
        except GeneratorExit:
            pass
    

    We’ll initialize the coroutine with a tally defaultdict, and get it ready to accept values by sending a None value to it:

    # init coroutine
    tally = defaultdict(int)
    c = tallyAccumulator(tally)
    c.send(None)
    

    We could use a for loop or a list comprehension to send all of the generator values to the coroutine:

    for val in generator1():
        c.send(val)
    

    or

    [c.send(val) for val in generator1()]
    

    But instead, we’ll use a zero-sized deque to process all the generator expression’s values without creating an unnecessary temporary list of None’s:

    # create generator expression consumer
    from collections import deque
    do_all = deque(maxlen=0).extend
    
    # loop thru generator at C speed, instead of Python for-loop speed
    do_all(c.send(val) for val in generator1())
    

    Now we look at the values again:

    for k in sorted(tally):
        print k, tally[k]
    

    And we get another list similar to the first one:

    1 52236
    2 49139
    3 51848
    4 51194
    5 51275
    6 50012
    7 51875
    8 46013
    9 50955
    10 52192
    

    Read more about coroutines at David Beazley’s page: http://www.dabeaz.com/coroutines/

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

A generator expression is throwing off a large number of tuple pairs eg. in
I have a generator (numbers) and a value (number). I would like to iterate
When should you use map/filter instead of a list comprehension or generator expression?
Suppose I have a list of sets and I want to get the union
I want to determine if a list contains a certain string, so I use
I've got a list of integers and I want to be able to identify
When iterating over a large array with a range expression, should I use Python's
It appears that using [] around a generator expression (test1) behaves substantially better than
I'm trying to write a simple generator that uses an expression tree to dynamically
I can use if and for in list comprehensions/generator expressions as list(i for i

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.