简体   繁体   中英

How can I get my function to return more than 1 result (with for-loops and dictionaries) in Python?

I am trying to find a way to return more than one result for my dictionary in Python:

def transitive_property(d1, d2):
    '''
    Return a new dictionary in which the keys are from d1 and the values are from d2. 
    A key-value pair should be included only if the value associated with a key in d1
    is a key in d2.  

    >>> transitive_property({'one':1, 'two':2}, {1:1.0})
    {'one':1.0}
    >>> transitive_property({'one':1, 'two':2}, {3:3.0})
    {}
    >>> transitive_property({'one':1, 'two':2, 'three':3}, {1:1.0, 3:3.0})
    {'one':1.0}
    {'three': 3.0}
    '''
    for key, val in d1.items():
        if val in d2:
            return {key:d2[val]}
        else:
            return {}

I've come up with a bunch of different things but they would never pass a few test cases such as the third one (with {'three':3}). This what results when I test using the third case in the doc string:

{'one':1.0}

So since it doesn't return {'three':3.0}, I feel that it only returns a single occurrence within the dictionary, so maybe it's a matter of returning a new dictionary so it could iterate over all of the cases. What would you say on this approach? I'm quite new so I hope the code below makes some sense despite the syntax errors. I really did try.

empty = {}
for key, val in d1.items():
    if val in d2:
        return empty += key, d2[val]

return empty

If return is used to , then the function is terminated for that particular call . So if you want to return more than one value it is impossible. You can use arrays instead .You can store values in array and the return thhe array.

Your idea almost works but (i) you are returning the value immediately, which exits the function at that point, and (ii) you can't add properties to a dictionary using += . Instead you need to set its properties using dictionary[key] = value .

result = {}
for key, val in d1.items():
    if val in d2:
        result[key] = d2[val]

return result

This can also be written more succinctly as a dictionary comprehension:

def transitive_property(d1, d2):
    return {key: d2[val] for key, val in d1.items() if val in d2}

You can also have the function return a list of dictionaries with a single key-value pair in each, though I'm not sure why you would want that:

def transitive_property(d1, d2):
    return [{key: d2[val]} for key, val in d1.items() if val in d2]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM