Python映射dicts

时间:2017-03-01 18:55:11

标签: python dictionary

假设我有一些包含月份的词典'短名称和一些数据

data_in = {"Jan":2.0, "Feb":5.5} 

和一些包含映射的dicts

month_names = {"Jan":"January", "Feb":"February"}
day_month = {day:"Jan" for day in range(1,32)}
day_month.update({day:"Feb" for day in range(32,60)})

如何获取包含长名称和天数作为元组的原始数据的以下dict?

{("January", 1):2.0, ("January", 2):2.0 ...}

2 个答案:

答案 0 :(得分:2)

继承我自己的尝试 -

from itertools import count
c = count(1,1)
days = {"Feb" : 28, "Jan" : 31}

mapping = {(month_names[i], next(c)) : data_in[i]  for i in data_in.keys()  for _ in range(days[i])}

print (mapping)

或使用您的day_month词典

mapping = {(month_names[day_month[i]], i) : data_in[day_month[i]] for i in day_month.keys()} 

print mapping 

输出 -

{('January', 1): 2.0,
 ('January', 2): 2.0,
 ('January', 3): 2.0,
 ('January', 4): 2.0,
 ('January', 5): 2.0,
 ('January', 6): 2.0,
 ('January', 7): 2.0,
 ('January', 8): 2.0,
 ('January', 9): 2.0,
 ('January', 10): 2.0,
 ('January', 11): 2.0,
 ('January', 12): 2.0,
 ('January', 13): 2.0,
 ('January', 14): 2.0,
 ('January', 15): 2.0,
 ('January', 16): 2.0,
 ('January', 17): 2.0,
 ('January', 18): 2.0,
 ('January', 19): 2.0,
 ('January', 20): 2.0,
 ('January', 21): 2.0,
 ('January', 22): 2.0,
 ('January', 23): 2.0,
 ('January', 24): 2.0,
  ..... }

答案 1 :(得分:0)

看起来你想要做的就是遍历day_month字典的键,并且每个字符都取month_namesdata_in的值的匹配条目,所以它应该看起来像:

result = {}
for day in day_month.keys():
    short_month = day_month[day]
    data = data_in[short_month]
    name = month_names[short_month]
    new_key = (name, day)
    result[new_key] = data