11
def foo(choice):
    for i in limit:
        d1 = doSomeCalc()
        d2 = doSomeOtherCalc()
        if choice == "stuff":
            yield {
                d1 : "value"
            }
        else:
            yield {
                d2 : "Othervalue"
            }

I have a function that yields two types of dictionaries depending upon the user's choice

def bar():
    for i in limit:
        d1 = doSomeCalc()
        d2 = doSomeOtherCalc()
        return {d1 : "value"}, {d2 : "Othervalue"}

a,b = bar() // when function returns two dictionaries

Just like return can I use yield to give two different dictionaries at a time? How will I get each value?

I don't want to keep the if-else in my function now.

Animesh Pandey
  • 5,900
  • 13
  • 64
  • 130
  • You can do it with: `yield dict1, dict2` which will yield a tuple of dictionaries, and if that's assigned to `a, b`, then each will be assigned the corresponding dictionary. (You don't need to index the tuple's values with `[]` to use them.) – martineau Jan 29 '15 at 01:43
  • Yeah, I earlier had an if-else where I was getting one dict at a time but there is no such requirement. I want both dicts and I'll send each to a seperate function – Animesh Pandey Jan 29 '15 at 01:43

2 Answers2

10

You can only yield a single value at a time. Iterating over the generator will yield each value in turn.

def foo():
  yield 1
  yield 2

for i in foo():
  print(i)

And as always, the value can be a tuple.

def foo():
  yield 1, 2

for i in foo():
  print(i)
AsukaMinato
  • 1,017
  • 12
  • 21
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
0

Another approach is to yield a data structure like a dictionary, as follows:

def create_acct_and_tbl():
    yield {'acct_id': 4, 'tbl_name': 'new_table_name'}


def test_acct_can_access():
    rslt = create_acct_and_tbl
    print(str(rslt['acct_id']), rslt['tbl_name'])
Ben
  • 4,798
  • 3
  • 21
  • 35