Home > Software engineering >  Create a function dictionary
Create a function dictionary

Time:03-27

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')

CodePudding user response:

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]

CodePudding user response:

Possible solution is the following:

data = {'España': 'la capiral es Madrid', 'Francia': 'la capital es Paris', 'Italia': 'la capital es Roma'}


def check_dict_key(data):
    values = []
    for k, v in data.items():
        if k in ['España', 'Francia']:
            values.append(v)
    if values:
        return values
    else:
        return "fail"
    
check_dict_key(data)

Returns

['la capiral es Madrid', 'la capital es Paris']
  • Related