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.
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
itemandpricealways go together. So the two pieces of data might as well be paired in an object:Similarly, a person seems to have an
idandnameand a set of possessions:If you buy into the idea of using classes like these, then your
list_dictscould becomeThen, to merge the people based on
id, you could use Python’sreducefunction,along with
take_items, which takes (merges) the items from one person and gives them to another:Putting it all together: