词典列表设置理解计算

时间:2018-05-22 15:36:37

标签: python-3.x list datetime dictionary

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

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'键日期的最简单方法是运行这个dict理解:

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))

现在,我需要做两件事:1)将这个列表拉回到'dl'键,然后2)返回或打印一组(随机)2个词组,不改变原始词典,也许就像这样:

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

干杯

0 个答案:

没有答案