简体   繁体   中英

How do I use the if-else function with timestamp in dictionary?

dict= {'Lemon': Timestamp('2022-05-01 00:00:00'), 'Orange': Timestamp('2020-09-06 00:00:00')}

input = Lemon

for k, v in dict.items():
    if input == k and v == '2022-05-01 00:00:00':
        print('Yes')
    elif input == k and v != '2022-05-01 00:00:00':
        print('Maybe')
    else:
        print('No')

The output i'm getting now is 'Maybe' and it repeats throughout the whole dictionary. How do I get the output Yes once?

Don't loop through the dictionary. Just test whether the key exists with in , and test the value by indexing.

fruits_dict = {'Lemon': Timestamp('2022-05-01 00:00:00'), 'Orange': Timestamp('2020-09-06 00:00:00')}
input_fruit = 'Lemon'

if input_fruit in fruits_dict:
    if fruits_dict[input_fruit] == Timestamp('2022-05-01 00:00:00'):
        print("Yes")
    else:
        print("No")
else:
    print("Maybe")

Making an assumption about the Timestamp class.

class Timestamp:
    def __init__(self, ts):
        self.ts = ts

    def __eq__(self, other):
        if isinstance(other, str):
            return self.ts == other
        if isinstance(other, type(self)):
            return self.ts == other.ts
        return False


dict_ = {'Lemon': Timestamp('2022-05-01 00:00:00'),
         'Orange': Timestamp('2020-09-06 00:00:00')}

fruit = 'Lemon'

if (v := dict_.get(fruit)):
    print('Yes' if v == '2022-05-01 00:00:00' else 'Maybe')
else:
    print('No')

Output:

Yes

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