【问题标题】:Recursing in nested dictionaries and lists在嵌套字典和列表中递归
【发布时间】:2018-08-21 13:41:47
【问题描述】:

这是我之前的一个问题的后续问题。我有一些字典,我需要查看它们包含的每个值,如果该值是日期时间,我需要以特定方式对其进行格式化。我还需要能够递归到嵌套字典和列表中。这是我目前所拥有的:

def fix_time(in_time):
    out_time = '{}-{:02d}-{:02d} {:02d}:{:02d}:{:02d}'.format(in_time.year, in_time.month, in_time.day, in_time.hour, in_time.minute, in_time.second)
    return out_time

def fix_recursive(dct):
    for key, value in dct.items():
        if isinstance(value, datetime.datetime):
            mydict[key] = fix_time(value)
        elif isinstance(value, dict):
            fix_recursive(value)    

mydict={
    'Field1':'Value1'
    'SomeDateField1':1516312413.729,
    'Field2':'Value2',
    'Field3': [
        {
           'Subfield3_1':'SubValue1',
           'SubDateField3_1':1516312413.729
        },
        {
           'Subfield3_2':'SubValue2',
           'SubDateField3_2':1516312413.729
        },
        {
           'Subfield3_3':'SubValue3',
           'SubDateField3_3':1516312413.729
        }
     ],
     'Field4': {
        'Subfield4_1':'SubValue1',
        'SubDateField4_1':1516312413.729
     }
}

fix_recursive(mydict)

这对于字典和嵌套字典非常有用,但对于列表则不太适用。因此,在上面的示例中,fix_recursive 将更正 SomeDateField1 和 SubDateField4_1,但不会更正 SubDateField3_1、SubDateField3_2 或 SubDateField3_3。此外,由于在获得输入之前我不知道输入会是什么样子,因此我正在尝试创建一个函数,该函数可以获取列出的嵌套 3 或 4 层深的值。

我们将不胜感激。

谢谢!

【问题讨论】:

  • 您可能会发现我感兴趣的代码here。另请参阅该答案末尾链接的我的其他代码。
  • 完全不相关,但是您的代码中有一个错误 - 您正在更新全局变量 mydict 而不是局部变量 dct。此外,您可能想了解datetime.strftime() 的日期时间格式。最后,您的字典中没有日期时间,只有时间戳(表示为浮点数)。
  • 很好看,@brunodesthuilliers!我想我们都犯过一次或两次“改变全局而不是局部”的错误。 :D
  • 正如布鲁诺所说,熟悉strftime 是个好主意。除了显式调用strftimedatetime 对象还知道如何使用这些代码格式化自己,因此您可以执行'{:%Y-%m-%d %H:%M:%S}'.format(in_time) 之类的操作

标签: python python-3.x nested


【解决方案1】:

您需要区分循环遍历列表和字典

def fix_recursive(obj):

    if isinstance(obj, list):  # could replace with collections.abc.MutableSequence
        itr = enumerate(obj)
    elif isinstance(obj, dict):  # could replace with collections.abc.MutableMapping
        itr = obj.items()
    else:
        return  # don't iterate -- pass back up

    for key, value in itr:
        if isinstance(value, datetime.datetime):
            obj[key] = fix_time(value)
        else:
            fix_recursive(value)

【讨论】:

    【解决方案2】:
    1. 流动您当前的路线,为递归函数添加列表支持。
    2. 为什么要使用 fix_time 来进行序列化和反序列化?使用 JSON 或 pickle,无需转换日期时间。

    【讨论】:

    • 这是评论,不是答案
    猜你喜欢
    • 2020-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-29
    • 2021-12-04
    • 2021-11-01
    相关资源
    最近更新 更多