I'm doing a db query as such select fruits from warehouse
.
The goal is to create a dictionary with the fruits in each warehouse:
{13: [apple, orange, grapes], 14: [banana, pineapple], 20: [strawberry, avocado, blueberry]}
Any fruits that are present in several warehouses I want to remove altogether and I want to print an error message about them. I got a solution that works but it requires several steps:
fruits = set()
duplicates = set()
stock = {}
tmp = []
for warehouse in warehouses:
for row in results:
if row[0] in fruits
print row[0] + " is a duplicate"
duplicates.add(row[0])
else
fruits.add(row[0])
tmp.append(row[0])
stock[warehouse] = tmp
tmp = []
final_result = {}
#Remove duplicates
for warehouse,fruits in stock.iteritems():
final_result[warehouse] = []
for fruit in fruits:
if fruit not in duplicates:
final_result[warehouse].append(fruit)
I like to use dict/list comprehension where I can but that seems ruled out here and the whole approach looks a bit cumbersome, is there a better/cleaner way to achieve the same result?