Satheesh Panduga
Satheesh Panduga

Reputation: 818

Couldn't group multiple elements in list of dictionaries in python

I have below code which is grouping id's based on location. Am trying to include st values in the result(f_loc) along with the respective id's, but it doesn't work

null=''
dataset={"users": [
    {"id": 20, "loc": "Chicago", "st":"4", "sectors": [{"sname": "Retail"}, {"sname": "Manufacturing"}, {"sname": null}]}, 
    {"id": 21, "loc": "Frankfurt", "st":"4", "sectors": [{"sname": null}]}, 
    {"id": 22, "loc": "Berlin", "st":"6", "sectors": [{"sname": "Manufacturing"}, {"sname": "Banking"},{"sname": "Agri"}]}, 
    {"id": 23, "loc": "Chicago", "st":"2", "sectors": [{"sname": "Banking"}, {"sname": "Agri"}]},
    {"id": 24, "loc": "Bern", "st":"1", "sectors": [{"sname": "Retail"}, {"sname": "Agri"}]},
    {"id": 25, "loc": "Bern", "st":"4", "sectors": [{"sname": "Retail"}, {"sname": "Agri"}, {"sname": "Banking"}]}
    ]}

byloc = lambda x: x['loc']

it = (
    (loc, list(user_grp))
    for loc, user_grp in itertools.groupby(
        sorted(dataset['users'], key=byloc), key=byloc
    )
)
fs_loc = [
    {'loc': loc, 'ids': [x['id'] for x in grp], 'count': len(grp)}
    for loc, grp in it
]

print(fs_loc)

Here is what I tried:

fs_loc = [
    {'loc': loc, 'ids': [x['id'],y['st'] for x,y in grp], 'count': len(grp)}
    for loc, grp in it
]

I also tried

fs_loc = [
    {'loc': loc, 'ids': [x['id','st'] for x in grp], 'count': len(grp)}
    for loc, grp in it
]

and

fs_loc = [
    {'loc': loc, 'ids': [x[{'id','st'}] for x in grp], 'count': len(grp)}
    for loc, grp in it
]

These doesn't work, what am I missing?

I would like to achieve the result as below -

[
{"loc": "Chicago","count":2,"ids": [{"id":"20","st":"4"}, {"id":"23","st":"2"}]}, 
{"loc": "Bern","count":2,"ids": [{"id":"24","st":"1"}, {"id":"25","st":"4"}]}, 
{"loc": "Frankfurt","count":1,"ids": [{"id":"21","st":"4"}]}, 
{"loc": "Berlin","count":1,"ids": [{"id":"21","st":"4"}]}    
]

or

[
{"loc": "Chicago","count":2,"ids": [{"20","4"}, {"23","2"}]}, 
{"loc": "Bern","count":2,"ids": [{"24","1"}, {"25","4"}]}, 
{"loc": "Frankfurt","count":1,"ids": [{"21","4"}]}, 
{"loc": "Berlin","count":1,"ids": [{"21","4"}]}    
]

Could you please suggest?

Upvotes: 0

Views: 26

Answers (1)

R Nar
R Nar

Reputation: 5515

'ids': [x['id'],y['st'] for x,y in grp]

should be something like:

'ids': [{'id':x['id'],'st':x['st']} for x in grp]

if you want the dictionary structure, or:

'ids': [[x['id'],x['st']] for x in grp]

if you want the list structure. Remember that grp is a list of dictionaries so you can't split it into 2 variables.

Upvotes: 1

Related Questions