python - Create unique dictionaries for two keys in a list of dictionaries -


i getting list of dictionaries in following format api, :

eg.

xlist =[     { "id":1, "day":2, name:"abc", ... },     { "id":1, "day":3, name:"abc", ... },     { "id":1, "day":2, name:"xyz", ... },     { "id":1, "day":3, name:"xyz", ... },...   ]    

so, store/optimize queries in db have convert them in format.

  • what efficient or other way generate following structure?

    unique_xlist =[   { "id":1, "day":2, name:["abc", "xyz"], ... },   { "id":1, "day":3, name:["abc", "xyz"], ... }, ]    

what doing :

 names = list(set([ v['name'] v in xlist])) #-- unique names  templist =  [{k:(names if k == 'name' else v) \            k, v in obj.items()} obj in xlist] #-- append unique names  unique_xlist= {v['day']:v v in templist}.values() #- find unique dicts 

i don't think efficient, using 3 loops find unique dicts day.

you use itertools.groupby:

from itertools import groupby  xlist.sort(key=lambda x: (x["id"], x["day"], x["name"]))  # or use sorted() unique_xlist = []  k, g in groupby(xlist, lambda x: (x["id"], x["day"])):     unique_xlist.append({"id": k[0], "day": k[1], "name": [i["name"] in g]}) 

Comments

Popular posts from this blog

ruby - Trying to change last to "x"s to 23 -

jquery - Clone last and append item to closest class -

c - Unrecognised emulation mode: elf_i386 on MinGW32 -