JUSTIN KPAKPA
JUSTIN KPAKPA

Reputation: 35

How do i obtain the value of an item in a conditional statement?

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

Answers (2)

FLAK-ZOSO
FLAK-ZOSO

Reputation: 4102

in


In Python exists a keyword called in, which is used in several ways.
For example:

>>> 'i' in "in"
True

.keys() and .values()


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.

Answer


You can do like this:

names = {"one":"john", "two":"justin"}
prompt = input("enter name: ")
if prompt in names.values():
    print("Hey, I'm here")

Edit


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

NMech
NMech

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

Related Questions