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 554361
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 13, 20262026-05-13T11:42:05+00:00 2026-05-13T11:42:05+00:00

Python newb here looking for some assistance… For a variable number of dicts in

  • 0

Python newb here looking for some assistance…

For a variable number of dicts in a python list like:

list_dicts = [
{'id':'001', 'name':'jim', 'item':'pencil', 'price':'0.99'},
{'id':'002', 'name':'mary', 'item':'book', 'price':'15.49'},
{'id':'002', 'name':'mary', 'item':'tape', 'price':'7.99'},
{'id':'003', 'name':'john', 'item':'pen', 'price':'3.49'},
{'id':'003', 'name':'john', 'item':'stapler', 'price':'9.49'},
{'id':'003', 'name':'john', 'item':'scissors', 'price':'12.99'},
]

I’m trying to find the best way to group dicts where the value of key “id” is equal, then add/merge any unique key:value and create a new list of dicts like:

list_dicts2 = [
{'id':'001', 'name':'jim', 'item1':'pencil', 'price1':'0.99'},
{'id':'002', 'name':'mary', 'item1':'book', 'price1':'15.49', 'item2':'tape', 'price2':'7.99'},
{'id':'003', 'name':'john', 'item1':'pen', 'price1':'3.49', 'item2':'stapler', 'price2':'9.49', 'item3':'scissors', 'price3':'12.99'},
]

So far, I’ve figured out how to group the dicts in the list with:

myList = itertools.groupby(list_dicts, operator.itemgetter('id'))

But I’m struggling with how to build the new list of dicts to:

1) Add the extra keys and values to the first dict instance that has the same “id”

2) Set the new name for “item” and “price” keys (e.g. “item1”, “item2”, “item3”). This seems clunky to me, is there a better way?

3) Loop over each “id” match to build up a string for later output

I’ve chosen to return a new list of dicts only because of the convenience of passing a dict to a templating function where setting variables by a descriptive key is helpful (there are many vars). If there is a cleaner more concise way to accomplish this, I’d be curious to learn. Again, I’m pretty new to Python and in working with data structures like this.

  • 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-13T11:42:06+00:00Added an answer on May 13, 2026 at 11:42 am

    Try to avoid complex nested data structures. I believe people tend to
    grok them only while they are intensively using the data structure. After the
    program is finished, or is set aside for a while, the data structure quickly
    becomes mystifying.

    Objects can be used to retain or even add richness to the data structure in a saner, more organized way. For instance, it appears the item and price always go together. So the two pieces of data might as well be paired in an object:

    class Item(object):
        def __init__(self,name,price):
            self.name=name
            self.price=price
    

    Similarly, a person seems to have an id and name and a set of possessions:

    class Person(object):
        def __init__(self,id,name,*items):
            self.id=id
            self.name=name
            self.items=set(items)
    

    If you buy into the idea of using classes like these, then your list_dicts could become

    list_people = [
        Person('001','jim',Item('pencil',0.99)),
        Person('002','mary',Item('book',15.49)),
        Person('002','mary',Item('tape',7.99)),
        Person('003','john',Item('pen',3.49)),
        Person('003','john',Item('stapler',9.49)),
        Person('003','john',Item('scissors',12.99)), 
    ]
    

    Then, to merge the people based on id, you could use Python’s reduce function,
    along with take_items, which takes (merges) the items from one person and gives them to another:

    def take_items(person,other):
        '''
        person takes other's items.
        Note however, that although person may be altered, other remains the same --
        other does not lose its items.    
        '''
        person.items.update(other.items)
        return person
    

    Putting it all together:

    import itertools
    import operator
    
    class Item(object):
        def __init__(self,name,price):
            self.name=name
            self.price=price
        def __str__(self):
            return '{0} {1}'.format(self.name,self.price)
    
    class Person(object):
        def __init__(self,id,name,*items):
            self.id=id
            self.name=name
            self.items=set(items)
        def __str__(self):
            return '{0} {1}: {2}'.format(self.id,self.name,map(str,self.items))
    
    list_people = [
        Person('001','jim',Item('pencil',0.99)),
        Person('002','mary',Item('book',15.49)),
        Person('002','mary',Item('tape',7.99)),
        Person('003','john',Item('pen',3.49)),
        Person('003','john',Item('stapler',9.49)),
        Person('003','john',Item('scissors',12.99)), 
    ]
    
    def take_items(person,other):
        '''
        person takes other's items.
        Note however, that although person may be altered, other remains the same --
        other does not lose its items.    
        '''
        person.items.update(other.items)
        return person
    
    list_people2 = [reduce(take_items,g)
                    for k,g in itertools.groupby(list_people, lambda person: person.id)]
    for person in list_people2:
        print(person)
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 366k
  • Answers 366k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer Using Sql Server CTE and ROW_NUMBER you could try using… May 14, 2026 at 4:28 pm
  • Editorial Team
    Editorial Team added an answer There is a way to wrap existing DOM elements, like… May 14, 2026 at 4:28 pm
  • Editorial Team
    Editorial Team added an answer I would leave the delete() method in place and create… May 14, 2026 at 4:28 pm

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

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.