Merge Lists While Showing Zeros In Python
I created a Django QuerySet which count values but unfortunately it do not show 0 values. Therefore I want to merge my two list like left join in SQL. I show my inputs and desired
Solution 1:
new_data = [ i['day'] + ' ' + str(i['count_1']) for i in query_1]
new_data.extend([ i['day'] + ' ' + str(i['count_1']) for i in query_2])
local_dict = {}
for values in new_data:
date, time, val = values.split()
if date in local_dict:
new_value = local_dict[date]
local_dict[date] = new_value.replace(new_value[-1],val)
else:
local_dict.setdefault(date,values+ (' %s' % '0'))
print(local_dict.values())
>>>
["2018-01-17 00:00:00+01:00 49 2",
"2018-01-16 00:00:00+01:00 139 6",
"2018-01-15 00:00:00+01:00 144 0",
"2018-01-14 00:00:00+01:00 142 2",
"2018-01-13 00:00:00+01:00 141 4",
"2018-01-12 00:00:00+01:00 144 0",
"2018-01-11 00:00:00+01:00 145 0",
"2018-01-10 00:00:00+01:00 95 0"]
Solution 2:
query_1 = [{'day': '2018-01-17 00:00:00+01:00','count_1': '49'},
{'day': '2018-01-16 00:00:00+01:00','count_1': '139'},
{'day': '2018-01-15 00:00:00+01:00','count_1': '144'},
{'day': '2018-01-14 00:00:00+01:00','count_1': '142'}]
query_2 = [{'day': '2018-01-17 00:00:00+01:00','count_2': '2'},
{'day': '2018-01-16 00:00:00+01:00','count_2': '6'},
{'day': '2018-01-15 00:00:00+03:00','count_2': '2'},
{'day': '2018-01-14 00:00:00+01:00','count_2': '4'}]
for a, b in zip(query_1, query_2):
if a['day'] == b['day']:
print a['day'] + " " + a['count_1'] + " " + b['count_2']
else:
print a['day'] + " " + a['count_1'] + " 0"
output:
2018-01-17 00:00:00+01:00 49 2
2018-01-16 00:00:00+01:00 139 6
2018-01-15 00:00:00+01:00 144 0
2018-01-14 00:00:00+01:00 142 4
Post a Comment for "Merge Lists While Showing Zeros In Python"