I am trying to build a function in python that yields values of two dictionaries IF a particular value from dict1 matches a particular value of dict2. My function looks like this:
def dict_matcher(dict1, dict2, item1_pos, item2_pos):
"""Uses a tuple value from dict1 to search for a matching tuple value in dict2. If a match is found, the other values from dict1 and dict2 are returned."""
for item1 in dict1:
for item2 in dict2:
if dict1[item1][item1_pos] == dict2[item2][item2_pos]:
yield(dict1[item1][2], dict2[item2][6])
I am using dict_matcher like this:
matches = [myresults for myresults in dict_matcher(dict1, dict2 , 2, 6)]
print(matches)
When I print matches I get a list of correctly matching dict1 and dict2 values like this:
[('frog', 'frog'), ('spider', 'spider'), ('cricket', 'cricket'), ('hampster', 'hampster')]
How can I add variable arguments to this function so that, in addition to printing the matching values from each dictionary, I can also print the other values of each dictionary item in instances where dict1[item1][2] and dict2[item2][6] match? Can I use *args? Thanks for the help.
EDIT:
Ok, there seems to be some confusion as to what I am trying to do so let me try another example.
dict1 = {1: ('frog', 'green'), 2: ('spider', 'blue'), 3: ('cricket', 'red')}
dict2 = {a: ('frog', 12.34), b: ('ape', 22.33), c: ('lemur', 90.21)}
dict_matcher(dict1, dict2, 0, 0) would find matching values for value[0] from dict1 and value[0] from dict2. In this case, the only match is ‘frog’. My function above does this. What I am trying to do is extend the function to be able to print out other values from the dictionary items where dict1[value][0] == dict2[value][0] I want this to be specified in the function argument.
You said you’re calling it as
You should be calling it as
and it’s signature is
So 4 arguments passed, and 4 named arguments. So
*argsresults inargs = None.I’m not sure exactly what you want, but if you do
You’ll get the same thing as you get from doing
If you want to get the whole matching items, do
If you want to get one item from each, but not the matching item, do
and
and
or whatever instead of 3 and 8.
If you want to get several, but not all items, do
and
and
or whatever instead of [2, 3] and [3, 8].
If this isn’t what you meant, let me know.