我的数据结构是一个字典列表。 我想在某些键的值上运行一个函数,然后输出一定数量的字典作为结果。
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个字符而不改变origianl字典,可能如下:
{'taskid':1,'desc':task1,'dl':8,'complexity':5} {'taskid':3,'desc':task3,'dl':8,'complexity':1}干杯
My data structure is a list of dicts. I would like to run a function over the values of certain keys, and then output only a certain number of dictionaries as the result.
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 durI found the easiest way to process the dates for the 'dl' key was to run this dict comprehension:
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))Now, I need to do 2 things: 1) zip this list back up to the 'dl' key, and 2)return or print a (random) set of 2 dicts w/o altering the origianl dict, perhaps like so:
{'taskid':1,'desc':task1,'dl':8,'complexity':5} {'taskid':3,'desc':task3,'dl':8,'complexity':1}Cheers
最满意答案
你可以像这样直接生成新的字典:
new_dicts = [{**d, 'dl': days(d['dl'])} for d in adict]如果你需要单独的val,你也可以用它来做到这一点:
new_dicts = [{**d, 'dl': v} for d, v in zip(adict, vals)]You could produce the new dicts directly like this:
new_dicts = [{**d, 'dl': days(d['dl'])} for d in adict]If you need vals separately, you can use it to do this as well:
new_dicts = [{**d, 'dl': v} for d, v in zip(adict, vals)]更多推荐
发布评论