[英]Compare dictionary keys (datetime) with list of tuples[1] and if matches return tuple[0]
I am a beginner(ish) with Python and having trouble with getting the correct syntax for this.我是 Python 的初学者,在获得正确的语法方面遇到了麻烦。 Any help is greatly appreciated!
任何帮助是极大的赞赏!
I have a dictionary and a list of tuples.我有一本字典和一个元组列表。 I would like to compare the key of my dictionary to a value in the tuple, and if meets criteria return a different tuple value.
我想将字典的键与元组中的值进行比较,如果满足条件,则返回不同的元组值。 Here's the illustration:
这是插图:
dictionary = {datetime.datetime(2022, 4, 12, 9, 30): 30, datetime.datetime(2022, 4, 12, 11, 0): 60, datetime.datetime(2022, 4, 12, 13, 0): 30}
tuplelist = [(1, datetime.time(6, 45, 21)), (2, datetime.time(7, 15, 21)), (3, datetime.time(7, 45, 21)...etc)
The goal is to see which increment of 30 minutes my dictionary key falls into, and update it with the increment number stored in tuple list.目标是查看我的字典键落入哪个 30 分钟增量,并使用存储在元组列表中的增量编号更新它。 What I tried:
我尝试了什么:
for k,y in dictionary:
for i, t in tuplelist:
if t <= k <= (t+ datetime.timedelta(minutes = 30)):
dictionary[k] = t
The error I got is unable to unpack non iterable type datetime.我得到的错误是无法解压不可迭代类型的日期时间。
Any help and/or explanation is welcome.欢迎任何帮助和/或解释。 I am really enjoying learning to code but not from a CS background so always looking for the how it works in addition to just the correct syntax.
我真的很喜欢学习编码,但不是来自 CS 背景,所以除了正确的语法之外,我总是在寻找它是如何工作的。
Thank you!谢谢!
Update for working solution:工作解决方案的更新:
newdic = {}
for k,v in dictionary.items():
for item in mylist:
i, t = item
if t <= k.time() <= (datetime.combine(datetime.today(),t) + datetime.timedelta(minutes=30)).time():
newdic.update({i : v})
else:
continue
This is not the complete answer.这不是完整的答案。 See if it helps resolve early issues up to the comment.
看看它是否有助于解决早期问题直到发表评论。
import datetime
dictionary = {datetime.datetime(2022, 4, 12, 9, 30): 30,
datetime.datetime(2022, 4, 12, 11, 0): 60,
datetime.datetime(2022, 4, 12, 13, 0): 30}
tuplelist = [(1, datetime.time(6, 45, 21)), (2, datetime.time(7, 15, 21)),
(3, datetime.time(7, 45, 21),)]
for k, y in dictionary.items():
for item in tuplelist: # get each tuple from the list
i, t = item # unpack the tuple into i and t
print(f'{i=} {t=}') # Check i and t values
# if t <= k <= (t + datetime.timedelta(minutes=30)):
# dictionary[k] = t
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.