If Python matches a certain variable with a dictionary key value, you want to create a syntax that outputs a dictionary value. Help me, T...T

Asked 2 years ago, Updated 2 years ago, 59 views

Q: If a certain variable value matches a dictionary key value with Python, you want to create a syntax that outputs a value value.

For example,

Season = "Spring" s_fruit = { 'Spring' : 'Strawberry', 'Summer' : 'Watermelon'}

Season's spring If the spring of s_fruit matches, This is an example where you want to print only the value 'strawberry'.

First of all, I write get in if, so it's printed as below.

if fruit_dir.get(season):

print(s_fruit.values()) 

-> [Strawberry, Plum] I think it's because it's printed only with the value of spring.

A matching value was pulled from the conditional statement, but nothing was output.

if season == s_fruit.keys():

print(s_fruit.values()) 

What syntax should I modify? Help me T..T

dictionary

2022-09-20 19:17

2 Answers

>>> Season = 'Spring'
>>> s_fruit = { 'Spring' : 'Strawberry', 'Summer' : 'Watermelon'}
>>> s_fruit[season]
"Strawberries."
>>> s_fruit.get(season)
"Strawberries."
>>> Season = 'Autumn'
>>> s_fruit[season]
Traceback (most recent call last):
  File "<pyshell#12>", line 1, in <module>
    s_fruit[season]
KeyError: 'Autumn'
>>> if season not in s_fruit:
    print("no fruit for", season)


No fruit for autumn


2022-09-20 19:17

Thank you so much for your answer. There's no place to ask I was struggling by myself and cried. I'll deal with it bravely from now on. ^ Thanks once again.

^


2022-09-20 19:17

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.