0

I have an unknown number of dictionaries each identified by a specific code.

All of the values are create dynamically, so the codes to group by are unknown.
I am hoping someone might be able to help me identify the best way to group the dictionaries so that I can then move through each to produce a table. There are actually about 7 items in the dictionary.

Each dictionary is a row in the table.

example:

results = ['GROUP1':{'name':'Sam', 'code':'CDZ', 'cat_name':'category1',   'cat_code':'GROUP1'}, 'GROUP1':{'name':'James', 'code':'CDF', 'cat_name':'category1',   'cat_code':'GROUP1'}, 'GROUP2':{'name':'Ellie', 'code':'CDT', 'cat_name':'category2',   'cat_code':'GROUP2'}] 

I want to be able to format these dictionaries into a table using to produce the following:

GROUP1 - category1
CODE | NAME

CDZ | Sam
CDF | James

GROUP2 - category2
CODE | NAME

CDT | Ellie

Thanks so much in advance.

2 Answers 2

1

If results is a list of dicts like this

>>> results = [
...     {'name': 'Sam', 'code': 'CDZ', 'cat_name': 'category1', 'cat_code': 'GROUP1'},
...     {'name': 'James', 'code': 'CDF', 'cat_name': 'category1', 'cat_code': 'GROUP1'},
...     {'name': 'Ellie', 'code': 'CDT', 'cat_name': 'category2', 'cat_code': 'GROUP2'}] 
>>> from collections import defaultdict
>>> D = defaultdict(list)
>>> for item in results:
...  D[item['cat_code'], item['cat_name']].append((item['code'], item['name']))
... 
>>> import pprint
>>> pprint.pprint(dict(D))
{('GROUP1', 'category1'): [('CDZ', 'Sam'), ('CDF', 'James')],
 ('GROUP2', 'category2'): [('CDT', 'Ellie')]}

You can iterate through D.items() and do whatever you like

Sign up to request clarification or add additional context in comments.

1 Comment

Perfect! Thank you! I knew it had to be simpler than I was making it.
0

Your first two problems are that your example input is not valid Python (the dict literal syntax is {}, not []), and you cannot have two identical keys in one dict. Until you fix these, we can't do anything. I'm not sure how you'd want to fix the duplicate keys problem--maybe you actually want an array of dicts instead of a dict of dicts?

1 Comment

Ah! Yes I think you are right actually! I might be back soon with an edit.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.