0

I really love shrinking my code into as few lines as possible. I have the code below and I been trying to get it into one line, if anyone can advise, i would appreciate it.

        list_choices = {}
        if_changed = ''
        for i in obj:
            if if_changed!=i.area.region.id:
                if_changed = i.area.region.id
                list_choices.setdefault(if_changed, [])

            list_choices[if_changed].append([i.id, i.name])
3
  • 5
    It's hard to help when you don't describe what you're trying to do or give the desired output. Commented Sep 1, 2011 at 18:12
  • Because your loop is stateful, anything I can come up with would be much harder to read, and probably longer, than the original.
    – wberry
    Commented Sep 1, 2011 at 18:13
  • 1
    In the code presented here, monitoring when i.area.region.id changes is not necessary. If it were, one could use itertools.groupby rather than this technique. Commented Sep 1, 2011 at 19:00

2 Answers 2

4
list_choices = {}
for i in obj:
    list_choices.setdefault(i.area.region.id, []).append([i.id, i.name])

or, using list_choices = collections.defaultdict(list) the last line will be:

list_choices[i.area.region.id].append([i.id, i.name])
0

Not very clear what you want to do, so I'm guessing you want to group things in obj by their area.region.id and then add them to a dictionary:

import itertools

list_choices = {}
obj_by_region = itertools.groupby(obj, key=lambda x: x.area.region.id)
for region, elements in obj_by_region:
    list_choices[region] = [[el.id, el.name] for el in elements]

Not the answer you're looking for? Browse other questions tagged or ask your own question.