打印特定值等于单独指定条件的指定词典

2024-09-28 22:30:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图做的只是从列表中提取日期值在特定月份内的字典

from datetime import date, datetime

listexample = []

def examplefunc():
  listexample.append(
    {'example_record':len(examplelist)+1,
     'date':datetime.strptime(input('Date (yyyy/mm/dd): ' ), '%Y/%m/%d'),
    })

examplefunc()

for i in listexample:
  print(listexample)

如果我将月份标准指定为“3”,则只应生成/打印日期中月份等于“3”的词典

如果在请求输入时输入'2020/02/01',则输出解析为:[{'example_record': 4, 'date': datetime.datetime(2020, 2, 1, 0, 0)}]

月份在字典条目中(如上例中的'2',但我只想提取'date'为==特定月份(或当前月份)的dict条目

我尝试在字典中遍历指定键值的列表,但这似乎也不起作用

下面是我一直在尝试的一个例子:

def show_all_in_current_month():
while True: 
    (examplelist[0]['date']).month == '{:%m}'.format(date.today())
    for i in range(len(examplelist)):
      print(examplelist)
    break

任何帮助都将不胜感激。谢谢大家!

编辑:这个(令人难以忍受的简单)解决方案对我的问题有效。谢谢大家的贡献

for d in examplelist:
 if str(d['date'].month) == '2':
  print(d)

Tags: in列表fordatetimedate字典exampledef
1条回答
网友
1楼 · 发布于 2024-09-28 22:30:42

您可以尝试以下方法:

from datetime import datetime
listexample=[]
def examplefunc():
  listexample.append(
    {'example_record':len(listexample)+1,
     'date':datetime.strptime(input('Date (yyyy/mm/dd): ' ), '%Y/%m/%d'),
    })

#Define how many dates are you going to add 
for i in range(int(input("How many dates are you going to add?\n:"))):
   examplefunc()

def show_all_in_current_month(currentmonth):   #receives the a month and filter the dicts that are in that month
   print([dict for dict in listexample if dict['date'].month==currentmonth])
show_all_in_current_month(int(input("Which month do you want to filter the list with?\n:")))

相关问题 更多 >