简体   繁体   中英

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

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM