更新字典列表中的值

Updating values in a dictionary list

假设您有一个字典,其中有一个日期列表(作为浮点数从 excel 中提取)作为县子字典中的一个值。

 master_dictionary = {'MO': {
   'Lincoln County': [43378.0, 43378.0, 43378.0],
   'Franklin County': [43357.0, 43357.0],
   'Camden County': [43208.0, 43208.0, 43208.0],
   'Miller County': [43208.0],
   'Morgan County': [43208.0, 43208.0]},
  'WI': {'Marathon County': [43371.0, 43371.0, 43371.0, 43371.0, 43371.0]},
  'NJ': {'Atlantic County': [43340.0, 43340.0]}}

我的目标是 1) 获得这些 'date' 的最大值,以及 2) 使用 datetime.strftime 将最大值 'date' 转换为 '%M/%D/%Y' 值。我能够获取最大值并将其转换,但我试图让它更新主词典中的日期值。我该怎么做?

for key, value in master_dictionary.items():
    counties = value
    for k, v in counties.items():
        d = max(v)
        year, month, day, hour, minute, second = xldate_as_tuple(d, book_datemode)
        n_date = rawDate = (str(month) + "/" + str(day) + "/" + str(year))
        print(n_date)

只需使用一些东西来获取 i = np.argmax(v) (numpy),这样您就有了索引,然后访问该位置并使用 master_dictionary[key][k][i] = n_date 进行更新。如果你想替换整个列表,使用 master_dictionary[key][k] = [n_date],你不需要 argmax 东西。祝你好运!

使用 库中的 xldate_as_datetime 函数:

for key, val in master_dictionary.items():
    for skey, sval in val.items():
        # temporary assignment to overwrite dates
        # with max for the given county (skey)
        cdate = xldate_as_datetime(max(sval),0).strftime('%m/%d/%Y')
        # assign the max date to 
        # the county in master_dictionry
        master_dictionary[key][skey] = cdate

通常最简单的方法是制作一本新字典,而不是尝试修改现有字典(如果您要添加或删除键,则尤其如此):

from xlrd import xldate_as_datetime
from pprint import pprint

new_dict = {k: {k1: xldate_as_datetime(max(v1),0).strftime('%m/%d/%Y') for k1, v1 in v.items()} 
            for k, v in master_dictionary.items()}

pprint(new_dict)

打印

{'MO': {'Camden County': '04/18/2018',
        'Franklin County': '09/14/2018',
        'Lincoln County': '10/05/2018',
        'Miller County': '04/18/2018',
        'Morgan County': '04/18/2018'},
 'NJ': {'Atlantic County': '08/28/2018'},
 'WI': {'Marathon County': '09/28/2018'}}