user2990084 user2990084 - 7 months ago 10
Python Question

Insert None while iterating list of months

I have a list with a range of year/month. Then, I also have a count of users with this format: total_users, month, year.

Basically I need to insert

None
when there is no count value for the month in all_months_necessary.

all_months_necessary=('2015/1', '2015/2', '2015/3', '2015/4', '2015/5', '2015/6', '2015/7', '2015/8', '2015/9', '2015/10', '2015/11', '2015/12', '2016/1')

users_count=[(2L, 1.0, 2015.0), (1L, 3.0, 2015.0), (1L, 1.0, 2016.0)]


I am trying this code, but the problem is that I will have more Nones than expected.

data=()
for each_month in all_months_necessary:
for total, month, year in users_count:
if each_month == str(int(year))+'/'+str(int(month)):
data = data + (total,)
else:
data = data + (None,)


expected:
data=(2L, None, 1L, None, None, ..., 1L)

Answer

It may be better to convert users_count to dictionary. Yet another onetwoliner:

user_count_dict = {str(int(year))+'/'+str(int(month)): total for total, month, year in users_count}
# get(x) returns None if a key not in the dict
data = [user_count_dict.get(x) for x in all_months_necessary]

And plus to Jason for explanations