1
    active_route_ids = self.env['route.data'].browse(active_ids)

    customer_contacts_group = {}

    for record in active_route_ids:
        for control in record.cust_control_pts:
            key_id = str(control.res_partner.id)

            if key_id not in customer_contacts_group:
                customer_contacts_group[key_id] = record
            else:
                customer_contacts_group[key_id].add(record)

Let's say we have dictionary like this:

  customer_contacts_group = {'1': (20,)}

I want to make it like this:

  customer_contacts_group = {'1': (20,30,40,)}

by appending values to customer_contacts_group['1'] one by one.

Andrea Corbellini
  • 17,339
  • 3
  • 53
  • 69
enigmq
  • 393
  • 5
  • 19
  • Possible duplicate of [Add Variables to Tuple](https://stackoverflow.com/questions/1380860/add-variables-to-tuple) – cuuupid Feb 09 '18 at 14:22

4 Answers4

1

You are dealing with tuples which can be concatenated:

customer_contacts_group[key_id] = customer_contacts_group[key_id] + record

Or, for short:

customer_contacts_group[key_id] += record
FlyingTeller
  • 17,638
  • 3
  • 38
  • 53
1

You can concatenate two tuples together to get your result. One thing to note is that tuples are not mutable in Python, however, you can assign the result of concatenating two immutable tuples to the variable holding the initial tuple, like you are wanting to do here.

customer_contacts_group['1'] += (4,5,6)

Output:

{'1': (20, 4, 5, 6)}
user3483203
  • 50,081
  • 9
  • 65
  • 94
0

You can access dictionary values using dictionary[key], but what you seem to be storing is not a list but a tuple. Tuples are immutable and so you cannot append values to them. You can, however, construct a new tuple by concatenation, e.g.

customer_contacts_group = {'1': (20,)}
customer_contacts_group['1'] = customer_contacts_group['1'] + (30,)

x['1'] is now (20,30). As long as both arguments being added are tuples, concatenation will occur.

cuuupid
  • 912
  • 5
  • 20
-1

You cannot append to tuples like your (20,30,40,). But to lists like [20, 30, 40].

And what you are trying to do calls for defaultdict(list) like so:

from collections import defaultdict
groups = defaultdict(list)
for key, record in [(1, 1), (1, 2), (2, 100), (2, 200)]:
    groups[key].append(record)

defaultdict(some_callable) saves you the hassle of checking whether a key exists etc. by defaulting to whatever some_callable returns.

j08lue
  • 1,647
  • 2
  • 21
  • 37