0

I'm trying to loop through a list of tuples and assign certain values in the tuple as a key to a dictionary, and other values of the tuple to the values of the dictionary. For some reason, every time I update an indexed value of a tuple key in the dictionary, the same indexed values for all of the keys is updated.

a = [('g', 'h', 'i', 1), ('a', 'b', 'c', 6), ('d', 'e', 'f', 1)]
b = [('a', 'b', 'c', 2), ('d', 'e', 'f', 5)]

Where the first three values of the tuple will become keys in a dictionary, and the last value will become a value in a list for that key.

output_dict = {}
tuple_lists = [a,b]
empty_values = [0]*len(tuple_lists)

for i, tuple_list in enumerate(tuple_lists):
    for key_value in tuple_list:
        key = key_value[:len(key_value)-1]
        value = key_value[len(key_value)-1:][0]
        if key not in output_dict:
            output_dict[key] = empty_values
            output_dict[key][i] = value
        else:
            output_dict[key][i] = value

This returns:

    {('g', 'h', 'i'): [1, 5], ('a', 'b', 'c'): [1, 5], ('d', 'e', 'f'): [1, 5]}

When I thought it should return:

    {('g', 'h', 'i'): [1, 0], ('a', 'b', 'c'): [6, 2], ('d', 'e', 'f'): [1, 5]}

The only hint I have is that the id for two different keys in output_dict are the same:

    id(output_dict[('g', 'h', 'i')])

returns the same value as:

    id(output_dict[('a', 'b', 'c')])
  • Just in case the linked question doesn't make sense to you, you can quickly fix the problem by replacing the line `output_dict[key] = empty_values` with `output_dict[key] = list(empty_values)`. – Blair Jun 12 '15 at 18:36
  • That worked perfectly! Thank you so much! – user1785609 Jun 12 '15 at 18:41

0 Answers0