Python Forum

Full Version: How to use value in dictionary as arguments in function
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
def test(data1, data2):
    eef = data1 + data2
    return(eef)

dict1 = {"a": (2, 2),
         "b": (3, 2),
         "c": (5, 6),
         "d": (1, 1)}
            
dict2 = {"f": (3, 1),
         "g": (1, 4)}

foo = test(dict1, dict2)
I want to add the value in dict1 with dict2 using function test but I don't know how to put the value in function
Create empty dict and call update() on this dict twice to add dict1 and dict2
I don't want to combine the dictionary, I just want to calculate the sum of value from dict1 and dict2

a:2 + f:3 = 5
a:2 + f:1 = 3
Sorry my English very bad
why match a and f? before 3.7 dicts are unordered collections, so it's not certain what order you will get...
and what will be the new key? a, f, af, something else...? Again tuple as value?
what about dicts with different len? what about dict values with different len?
ooh ok so it is not possible to use the tuple inside dictionary for the function
(Apr-22-2020, 04:46 PM)gabejohnsonny21 Wrote: [ -> ]it is not possible to use the tuple inside dictionary for the function
it is possible, however your "requirements" are unclear - there are huge gray areas about what you want as output and how expect to handle particular cases.
Something like this?
dict1 = {"a": (2, 2),
         "b": (3, 2),
         "c": (5, 6),
         "d": (1, 1)}
             
dict2 = {"f": (3, 1),
         "g": (1, 4)}

def add_it_up(d1, d2):
    d3 = {}
    for a, b in zip(d1.items(), d2.items()):
        a_key, a_values = a
        b_key, b_values = b
        d3[f'{a_key}+{b_key}'] = (a_values[0] + b_values[0], a_values[1] + b_values[1])
    return d3

print(add_it_up(dict1, dict2))
I have no idea what you want for output so I made a new dictionary making keys from the input dictionaries (a+f, b+g).

This would be a little easier using lists and a bit less odd. I know that dictionaries now maintain their order, but I think it strange to think of dictionaries as having order. You use keys in dictionaries. Lists on the other hand can only be referenced using their order. Maybe just a bias I need to get over.