'Create a function dictionary
I need a code in a function way, that contains a dictionary. The output have to be the dictionary value. I wrote this one but it doesn't work. Can someone help me?
def a(paisos):
d = {'España': 'la capiral es madrid', 'Francia': 'la capital es paris'}
paisos = d.keys
b = d.values
if paisos in d:
print(b)
else:
print('fail')
Solution 1:[1]
Lets start from the beginning...
paisos = d.keys
b = d.values
what you wrote doesn't make sense, since dict.values and dict.keys are methods (we may say they are functions) and not attributes, so you have to call them:
paisos = d.keys()
b = d.values()
if paisos in d:
What does it mean? d is an object of type dict, while paisos is a list (returned by d.keys())
If you want to get the value (the capital) from the key (the country) you have to do this:
def a(paisos):
...
capital = d[paisos]
[...] now the problem I have is that instead of printing fail when I write something that is not in the dictionary
No problem, you just have to use a try/except to handle a KeyError when the key doesn't exist in your dict (d):
try:
capital = d[paisos]
except KeyError as error: # The country doesn't exist
print("Something went wrong")
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
