从列表的元素中指定各种词典的名称

时间:2017-11-19 09:19:07

标签: python python-2.7 dictionary

我正在生成7个词典,代表一周中的一天。从压缩2列表生成字典。一切都工作正常,但我想删除代码中的一些冗余。让我们先看看代码

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))

所以基本上不是使用sunmon我想使用像

这样的东西
str(day_names[i+1]) = dict(zip(time_values,number_of_clients))

1 个答案:

答案 0 :(得分:0)

您要找的是locals(),例如:

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

另见globals()

但是,有点不鼓励使用locals()globals()。考虑使用字典来聚合这些值,例如:

d = dict()

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

d[day_names[i-1]] = dict(zip(time_values,number_of_clients))