219,018 views
29 votes
29 votes
In python please:

Assume the variable definitions references a dictionary. Write an ig statement that determined whether the key ‘marsupial’ exist in the dictionary. If so, delete ‘marsupial’ and it’s associated value. If the key is not the dictionary, display a message indicating so.

User ChapMic
by
2.6k points

1 Answer

27 votes
27 votes

Answer:

"

if 'marsupial' in dictionary:

del dictionary['marsupial']

else:

print("The key marsupial is not in the dictionary")

"

Step-by-step explanation:

So you can use the keyword "in" to check if a certain key exists.

So the following code:

"

if key in object:

# some code

"

will only run if the value of "key" is a key in the object dictionary.

So using this, we can check if the string "marsupial' exists in the dictionary.

"

if 'marsupial' in dictionary:

# code

"

Since you never gave the variable name for the variable that references a dictionary, I'm just going to use the variable name "dictionary"

Anyways, to delete a key, there are two methods.

"

del dictionary[key]

dictionary.pop(key)

"

Both will raise the error "KeyError" if the key doesn't exist in the dictionary, although there is method with pop that causes an error to not be raised, but that isn[t necessary in this case, since you're using the if statement to check if it's in the dictionary first.

So I'll just use del dictionary[key] method here

"

if 'marsupial' in dictionary:

del dictionary['marsupial']

else:

print("The key marsupial is not in the dictionary")

"

The last part which I just added in the code is just an else statement which will only run if the key 'marsupial' is not in the dictionary.

User Justin Wignall
by
2.9k points