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?
CodePudding user response:
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")
CodePudding user response:
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