unpacking a tuple within a UDF taking a tuple as argument

Viewed 44

I'm trying to create a function that takes a dictionary whose values are tuples, and a separate tuple as arguments, after which I am trying to compare between their index values as demonstrated below. If they match the key should be entered into a new dictionary.

I've been trying to use tuple unpacking and I'm not sure what I'm doing wrong (new to Python):

some_dict = {"a" : (1,2,3), "b" : (1,4,5), "c" : (2,2,3)}
some_tuple = (1,2,5)

def function (some_dict, *some_tuple):
    another_dict = {"match" : [], "no_match" : []}
    some_tuple = list(some_tuple)
    for item in some_dict.values():
        if some_dict[item][0] == some_tuple[0]:
            another_dict["match"].append(item)
        else:
            another_dict["no_match"].append(item)
    return another_dict
1 Answers

You first need to put * in front of some_tuple when you call the function.
OR you can also remove * in front of some_tuple in the function definition as well.

Also, when you iterating through some_dict, I think you don't want to use values method. Because I believe you want to iterate through the keys of the dict.

Try the following:

some_dict = {"a": (1, 2, 3), "b": (1, 4, 5), "c": (2, 2, 3)}
some_tuple = (1, 2, 5)


def function(some_dict, *some_tuple):
    another_dict = {"match": [], "no_match": []}
    some_tuple = list(some_tuple)
    for item in some_dict:
        if some_dict[item][0] == some_tuple[0]:
            another_dict["match"].append(item)
        else:
            another_dict["no_match"].append(item)
    return another_dict


print(function(some_dict, *some_tuple))
{'match': ['a', 'b'], 'no_match': ['c']}
Related