Skip to content

ENH: Add an iterdicts() function #60901

Open
@narukaze132

Description

@narukaze132

Feature Type

  • Adding new functionality to pandas

  • Changing existing functionality in pandas

  • Removing existing functionality in pandas

Problem Description

I wish I could iterate through dictionaries of each row's contents in a DataFrame, the same way I could do so with namedtuples through itertuples(). Performing the namedtuple-to-dict conversion process isn't difficult normally, but in some situation (e.g. doing so in a list/set/dict comprehension), it's more convenient to have a generator that does the process automatically for you.

Feature Description

Add a new function to DataFrames, iterdicts, that takes an index argument (equivalent to the same argument in itertuples) and returns each row as a dictionary the same way itertuples does so as a namedtuple. (No need to take a "name" argument, since that's irrelevant for dictionaries.)

def iterdicts(self, index=True):
    for x in self.itertuples(index):
        yield x._asdict()

Alternative Solutions

Write a custom function that does the same thing externally.

def iterdicts(df, index=True):
    for x in df.itertuples(index):
        yield x._asdict()

EDIT (4/4/25): Alternatively, use map and an anonymous function to create the generator.

map(lambda x: x._asdict(), df.itertuples())

Additional Context

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    Closing CandidateMay be closeable, needs more eyeballsEnhancementNeeds TriageIssue that has not been reviewed by a pandas team member

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions