简体   繁体   中英

Yielding a dictionary key, value pair in __iter__ method of a class

I have a super simple class:

class Person():
    def __init__(self, attributes_to_values):
        self.attributes_to_values =  attributes_to_values

which I use as follows:

attributes_to_values = dict(name='Alex', age=30, happiness=100)
alex = Person(attributes_to_values=attributes_to_values)

I want to iterate over alex such that I return the keys and corresponding values in attributes_to_values attribute.

I've tried inserting the following:

def __iter__(self):
    yield list(self.attributes_to_values.items())

but this doesn't work ...

for a, v in alex:
    print(a, v)

Traceback (most recent call last): File "", line 1, in ValueError: too many values to unpack (expected 2)

If you have an iterable like item() you can yield from it:

class Person():
    def __init__(self, attributes_to_values):
        self.attributes_to_values =  attributes_to_values

    def __iter__(self):
        yield from self.attributes_to_values.items()


attributes_to_values = dict(name='Alex', age=30, happiness=100)
alex = Person(attributes_to_values=attributes_to_values)

for a, v in alex:
    print(a, v)

prints

name Alex
age 30
happiness 100

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM