[英]Python mapping dicts
Suppose I have some dict containing months' short names and some data 假设我有一些字典,其中包含月份的简称和一些数据
data_in = {"Jan":2.0, "Feb":5.5}
and some dicts containing mappings 和一些包含映射的字典
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)})
How do I obtain the following dict containing the original data with the long name and the day number as a tuple? 如何获取以下包含原始数据的字典,该原始数据以长名称和天数作为元组?
{("January", 1):2.0, ("January", 2):2.0 ...}
Heres my own try - 这是我自己的尝试-
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)
OR using your day_month
dict 或使用您的
day_month
字典
mapping = {(month_names[day_month[i]], i) : data_in[day_month[i]] for i in day_month.keys()}
print mapping
Output - 输出-
{('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,
..... }
Seems like what you want to do is iterate over the keys of the day_month
dictionary, and for each take the matching entry for the value from month_names
and data_in
, so it should look something like: 似乎您要执行的操作是遍历
day_month
字典的键,并且每个键都从month_names
和data_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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.