0

I am generating 7 dictionaries which represent a day in a week. A dictionary is generated from zipping 2 lists. everything is working fine, but there is some redundancy in code which I want to remove. let us see the code first

day_names = ['mon','tue','wed','thurs','fri','sat','sun']

time_values = np.linspace(1,23,23,dtype='int') # print from 1,2...23

for day_iterator in range(1,7+1):


    number_of_clients = [] # create empty list that will hold number of clients
    for i in range(1,24,1):
        rand_value =  random.randint(1,20) # generate number of clients
        number_of_clients.append(rand_value)

    if day_iterator == 1:
        mon = dict(zip(time_values,number_of_clients))

    elif day_iterator == 2:
        tue = dict(zip(time_values,number_of_clients))

    elif day_iterator == 3:
        wed = dict(zip(time_values,number_of_clients))

    elif day_iterator == 4:
        thurs = dict(zip(time_values,number_of_clients))

    elif day_iterator == 5:
        fri = dict(zip(time_values,number_of_clients))

    elif day_iterator == 6:
        sat = dict(zip(time_values,number_of_clients))

    elif day_iterator == 7:
        sun = dict(zip(time_values,number_of_clients))

so basically instead of using sun, mon i want to use something like

str(day_names[i+1]) = dict(zip(time_values,number_of_clients))
Amarjit Dhillon
  • 2,718
  • 3
  • 23
  • 62

1 Answers1

0

What you are looking for is locals(), e.g.:

locals()[day_names[i-1]] = ...

See also globals()

However, the use of locals() or globals() is somewhat discouraged. Consider using a dictionary to aggregate these values, e.g.:

d = dict()

d['mon'] = dict(zip(time_values,number_of_clients))

d[day_names[i-1]] = dict(zip(time_values,number_of_clients))
fferri
  • 18,285
  • 5
  • 46
  • 95