Merge Multiple Lists Of Lists Based On Template
I have 3 DB calls returning a tuple of tuples with a name, code and count like so: year = (('Fanklin Grand Isle', '5560', 1), ('Windham', '3457', 1)) month = (('Fanklin Grand Isle'
Solution 1:
Here's a way to deal with your issue using a defaultdict
to avoid having to care about the missing entries :
year = (('Fanklin Grand Isle', '5560', 1), ('Windham', '3457', 1))
month = (('Fanklin Grand Isle', '5560', 1), ('Chittendon', '3367', 1))
week = (('Fanklin Grand Isle', '5560', 1), ('Chittendon', '3367', 1))
#I'm using a defaultdict to deal with the missing entriesfrom collections import defaultdict
joined_data = defaultdict([0,0,0].copy)
for entry in year:
#we create the default entry by calling the defaultdict with a key#and immediately grab the newly created list
count = joined_data[(entry[0],entry[1])]
#we swap *inplace* the value given by the DB query
count[0] = entry[2]
#rinse and repeat with the rest of the datafor entry in month:
count = joined_data[(entry[0],entry[1])]
count[1] = entry[2]
for entry in week:
count = joined_data[(entry[0],entry[1])]
count[2] = entry[2]
#Finally we format the data to the required format
result = tuple(key+tuple(value) for key,value in joined_data.items() )
print(result)
Output:
>>>(('Chittendon', '3367', 0, 1, 1), ('Fanklin Grand Isle', '5560', 1, 1, 1), ('Windham', '3457', 1, 0, 0))
Solution 2:
Not sure I understand what you are trying to achieve, as your example input does not really match your output, but I think you can just use a list comprehension to construct the result, checking whether those items are in the years
, months
and weeks
lists, and adding a 1
or 0
respectively:
>>>year= (('Fanklin Grand Isle', '5560', 1), ('Windham', '3457', 1))
>>>month= (('Fanklin Grand Isle', '5560', 1), ('Chittendon', '3367', 1))
>>> week = (('Fanklin Grand Isle', '5560', 1), ('Chittendon', '3367', 1))
>>> [(x[0], x[1], int(x inyear), int(x inmonth), int(x in week)) for x inset(year+ week +month)]
[('Chittendon', '3367', 0, 1, 1),
('Windham', '3457', 1, 0, 0),
('Fanklin Grand Isle', '5560', 1, 1, 1)]
If those counts can actually be different from 1
, you should first create a few dictionaries mapping the cities to their respective year/month/week counts, and then use a similar list comprehension as above:
>>> year_counts = {(name, code): count for (name, code, count) in year}
>>> month_counts = {(name, code): count for (name, code, count) in month}
>>> week_counts = {(name, code): count for (name, code, count) in week}
>>> all_cities = [(name, code) for (name, code, count) inset(year + month + week)]
>>> [(x[0], x[1], year_counts.get(x, 0), month_counts.get(x, 0), week_counts.get(x, 0)) for x in all_cities]
[('Chittendon', '3367', 0, 1, 1),
('Windham', '3457', 1, 0, 0),
('Fanklin Grand Isle', '5560', 1, 1, 1)]
Post a Comment for "Merge Multiple Lists Of Lists Based On Template"