I have a Dict
whs = {
'ID1' : ['code1', 'code2', 'code3'],
'ID2' : ['code2', 'code5', 'code3'],
'ID3' : ['code6', 'code7', 'code8'],
'ID4' : ['code3', 'code5', 'code6'],
}
What I need to do is build a new list that will look like
submit = [
{
'codes' : ['code3', ],
'ids' : ['ID1', 'ID2', 'ID4'],
},
{
'codes' : ['code6', 'code7', 'code8'],
'ids' : ['ID3', ],
}
]
What I have so far
def ParseAvailable(self, whs):
separate = whs.keys()
submit = []
while len(separate) > 0:
avail = {
'codes' : [],
'ids' : [],
}
for num, item in enumerate(separate):
if len(avail['codes']) == 0:
avail['codes'] = whs[item]
avail['ids'].append(item)
else:
avail_all = list(set(avail['codes']) & set(whs[item]))
print '%s : %s' % (item, avail_all)
if len(avail_all) > 0:
avail['codes'] = avail_all
avail['ids'].append(item)
if len(avail['codes']) > 0:
del separate[num]
submit.append(avail)
return submit
Which returns:
[
{
'ids': ['ID4', 'ID3'],
'codes': ['code6']
},
{
'ids': ['ID2'],
'codes': ['code2', 'code5', 'code3']
},
{
'ids': ['ID1'],
'codes': ['code1', 'code2', 'code3']
}
]
which COULD work except that ID1 & ID2 should be combined as
{
'ids' : ['ID1', 'ID2',],
'codes' : ['code2', 'code3', ]
}
Curious if there is an easier approach that I’ve not thought of, figure I could setup a couple more nested loops to compare everything piece by piece though it seems rather unpythonic
Thank You in Advance
I attacked it by building a tree of all the potential additions, and then finding the cheapest option among those. Here is a working (albeit ugly and unoptimized) example:
https://gist.github.com/1288835
The tree will end up with p*w nodes, where p is the number of products and w(p) is the average number of warehouses per product.