Reputation: 35
How do I obtain the value of a dictionary item in a conditional statement for instance
names = {"one":"john", "two":"justin"}
prompt = input("enter option: ")
if prompt == names["one"]:
print("hey, I am here")
What will you suggest I go about it with a solution similar to line 3 so that I if the user inputs a key for instance "one" it prints "john"
Upvotes: 0
Views: 58
Reputation: 4102
In Python exists a keyword called in
, which is used in several ways.
For example:
>>> 'i' in "in"
True
The dict built-in class has two methods: keys()
and values()
.
They're used like this:
>>> Dictionary = {"one":"john", "two":"justin"}
>>> Dictionary.keys()
["one", "two"]
>>> Dictionary.values()
["john", "justin"]
And they're also subscriptable, because they returns lists.
You can do like this:
names = {"one":"john", "two":"justin"}
prompt = input("enter name: ")
if prompt in names.values():
print("Hey, I'm here")
This should work:
# According to PEP-8 you should always leave a space after ':' in a dict
names = {"one": "john", "two": "justin"}
prompt = input("enter number: ")
if prompt in names.keys():
print(f"Hey, {names[prompt]} is here!")
Upvotes: 2
Reputation: 600
you could try in
names = {"one":"john", "two":"justin"}
prompt = input("enter name: ")
if prompt in names.values():
print("hey, I am here")
Upvotes: 0