简体   繁体   中英

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. 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. 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM