【问题标题】:List of dictionaries set comprehension calculation字典列表集理解计算
【发布时间】:2018-11-01 10:50:56
【问题描述】:

我的数据结构是一个字典列表。我想对某些键的值运行一个函数,然后只输出一定数量的字典作为结果。

from datetime import datetime
from dateutil.parser import parse

today = '05/17/18'
adict = [{'taskid':1,'desc':'task1','complexity':5,'dl':'05/28/18'},{'taskid':2,'desc':'task2','complexity':3,'dl':'05/20/18'},
         {'taskid':3,'desc':'task3','complexity':1,'dl':'05/25/18'}]

def conv_tm(t):
    return datetime.strptime(t,'%m/%d/%y')

def days(obj):
    day = conv_tm(today)
    dl = conv_tm(obj)
    dur = (dl-day).days
    if dur <0:
        dur = 1
    return dur

我发现处理“dl”键日期的最简单方法是运行这个字典理解:

vals = [days(i['dl']) for i in adict]

#this also worked, but I didn't like it as much
vals = list(map(lambda x: days(x['dl']), adict))

现在,我需要做 2 件事:1) 将此列表压缩回 'dl' 键,以及 2) 返回或打印一组(随机)2 个不改变原始字典的字典,也许像所以:

{'taskid':1,'desc':task1,'dl':8,'complexity':5}
{'taskid':3,'desc':task3,'dl':8,'complexity':1}

干杯

【问题讨论】:

    标签: python-3.x list datetime dictionary


    【解决方案1】:

    你可以像这样直接生成新的字典:

    new_dicts = [{**d, 'dl': days(d['dl'])} for d in adict]
    

    如果您需要单独的 val,您也可以使用它来执行此操作:

    new_dicts = [{**d, 'dl': v} for d, v in zip(adict, vals)]
    

    【讨论】:

    • 这是一个非常简单的方法!不知道你可以压缩这样的字典 - 非常有用,谢谢
    猜你喜欢
    • 2021-09-07
    • 2021-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多