【问题标题】:Updating values in a dictionary list更新字典列表中的值
【发布时间】:2019-02-21 15:19:43
【问题描述】:

假设您有一本字典,其中包含日期列表(从 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) 获取这些“日期”的最大值,2) 使用 datetime.strftime 将最大“日期”转换为 '%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)

【问题讨论】:

  • 你希望你的输出是什么样的?
  • 类似这样的:master_dictionary = {'MO': { 'Lincoln County': ['4/22/2018'], 'Franklin County': ['12/3/2017'], 'Camden County': ['7/11/2018'], 'Miller County': ['6/20/2018'],'Morgan County': ['6/6/2018']},'WI': {'Marathon County': ['12/21/2017']}, 'NJ': {'Atlantic County': ['10/5/2017']}} 基本上,每个县都有最新的日期。如果我可以让日期不再是列表项,而只是“县”子词典中的常规值,则奖励。

标签: python list dictionary python-3.6 updates


【解决方案1】:

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

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'}}

【讨论】:

    【解决方案2】:

    使用 库中的 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
    

    【讨论】:

      【解决方案3】:

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

      【讨论】:

      • 我猜 OP 不希望它成为一个列表。所以你的意思可能是master_dictionary[key][k] = n_date
      • 我稍微修改了这个解决方案,效果很好。一般来说,我的问题是实际问题的简化版本,但同时使用master_dictionary[key][k] = n_datemaster_dictionary[key][k] = [n_date] 似乎在我的情况下工作。谢谢!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-16
      相关资源
      最近更新 更多