How can I get my function to return more than 1 result (with for-loops and dictionaries) in Python? -
i trying find way homecoming more 1 result dictionary in python:
def transitive_property(d1, d2): ''' homecoming new dictionary in keys d1 , values d2. key-value pair should included if value associated key in d1 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} ''' key, val in d1.items(): if val in d2: homecoming {key:d2[val]} else: homecoming {}
i've come bunch of different things never pass few test cases such 3rd 1 (with {'three':3}). results when test using 3rd case in doc string:
{'one':1.0}
so since doesn't homecoming {'three':3.0}, sense returns single occurrence within dictionary, maybe it's matter of returning new dictionary iterate on of cases. on approach? i'm quite new hope code below makes sense despite syntax errors. did try.
empty = {} key, val in d1.items(): if val in d2: homecoming empty += key, d2[val] homecoming empty
your thought works (i) returning value immediately, exits function @ point, , (ii) can't add together properties dictionary using +=
. instead need set properties using dictionary[key] = value
.
result = {} key, val in d1.items(): if val in d2: result[key] = d2[val] homecoming result
this can written more succinctly dictionary comprehension:
def transitive_property(d1, d2): homecoming {key: d2[val] key, val in d1.items() if val in d2}
you can have function homecoming list of dictionaries single key-value pair in each, though i'm not sure why want that:
def transitive_property(d1, d2): homecoming [{key: d2[val]} key, val in d1.items() if val in d2]
python for-loop dictionary
No comments:
Post a Comment