字典列表设置理解计算(List of dictionaries set comprehension calculation)

编程入门 行业动态 更新时间:2024-10-04 21:23:09
字典列表设置理解计算(List of dictionaries set comprehension calculation)

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

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 dur

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

更多推荐

本文发布于:2023-07-09 10:13:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1085564.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字典   列表   List   dictionaries   comprehension

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!