0

(I'm just using things to represent the format my dictionary is like, this is not how it actually looks) The current dictionary I have is in the format of :

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

I am trying to add on to it. I have a function that calculated an average and now I want to create a second function that would pull that average from the first function and add it to the tuple in the values of my dictionary. So if the average was 4 for "a", then I would want to add it on for it to look like this {"a":(1,2,3,4)} etc.

def func1(dict, dict2, number):
   if number in dict:
      for num in dict.values():

       #return sum after iteration of sum through num[0] to num[2]

def func 2 (dict1, dict2)

    if number in dict:
       new_val_to_add= func1(dict, dict2, number)

From here I'm not sure where I would go with adding the returned value to the tuple and be able to print back dict with the added value. I was thinking of maybe converting the tuple in the first dictionary into a list and then append to that as I iterate through each key in the dictionary, and finally convert it back into a tuple. Would this be the right way of going about this?

idjaw
  • 25,487
  • 7
  • 64
  • 83
Nick
  • 97
  • 3
  • 11
  • tuples are [immutable](http://stackoverflow.com/questions/1538663/why-are-python-strings-and-tuples-are-made-immutable). For what you are trying to do, you need to create a new tuple that contains the data of the old and the new data you are adding. – idjaw Apr 15 '16 at 20:37
  • yes, I understand that tuples are immutable, so thats why I was thinking of converting it into a list by doing lets say: list(dict.values()) and add on to it that way and then changing it at the end back to a tuple before returning the dictionary – Nick Apr 15 '16 at 20:40
  • 2
    Can't you make your data structure friendlier to change since you are constantly changing the values? – idjaw Apr 15 '16 at 20:43

1 Answers1

1

If you want the values to be mutable, why don't you use lists instead of tuples?

You can combine two tuples using +, though:

>>> (1, 2, 3) + (4,)
(1, 2, 3, 4)

I'm having trouble following your example code, but with a dictionary following your description you can do it like this:

>>> d1 = {'a': (1, 2, 3)}
>>> d1['a'] += (4,)
>>> d1
{'a': (1, 2, 3, 4)}

Or, using a list instead:

>>> d1 = {'a': [1, 2, 3]}
>>> d1['a'].append(4)
>>> d1
{'a': [1, 2, 3, 4]}
reupen
  • 571
  • 3
  • 8