[英]Finding the values of dictionary while looping through a list
我有一個包含員工及其出勤數據的字典列表。 我想找到記錄存在於列表中的日期列表(可能有 2 個相同的日期)以及它不存在的日期。
attendance_list = [
{'employee_name': 'Bob', 'attendance_date': '2021-04-01', 'status': 'Present'},
{'employee_name': 'Bob', 'attendance_date': '2021-04-05', 'status': 'Present'},
{'employee_name': 'Bob', 'attendance_date': '2021-04-08', 'status': 'Half Day'},
{'employee_name': 'Bob', 'attendance_date': '2021-04-08', 'status': 'On Leave'},
{'employee_name': 'Bob', 'attendance_date': '2021-04-09', 'status': 'On Leave'}
]
示例:從 2021-04-01 到 2021-04-10
我想從列表中提取日期列表並循環遍歷日期,但是如何在里面找到字典的值?
dates = ['2021-04-01', '2021-04-02', '2021-04-03', '2021-04-04',
'2021-04-05', '2021-04-06', '2021-04-07', '2021-04-08', '2021-04-09',
'2021-04-10']
attended_date = [d['attendance_date'] for d in attendance_list if 'attendance_date' in d]
for d in dates:
if d not in attended_date:
print("Not in List")
else:
print("In List") #get the values of dict
看起來您想要的列表是 Attendance_date 所在的attendance_date
attended_date
。 您可以使用列表理解 ( docs ) 來做到這一點。
[
attended_employee for attended_employee in attendance_list
if attended_employee['attendance_date'] in attended_date
]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.