Creating a new data structure while filtering its data origin.

attn.steven.kuo at gmail.com attn.steven.kuo at gmail.com
Thu Mar 29 11:24:16 EDT 2007


On Mar 28, 1:44 pm, <m... at fibertel.com.ar> wrote:
> Hi everyone.
>
> I'm trying to work with very simple data structures but I'm stuck in the very first steps. If someone has the luxury of a few minutes and can give an advice how to resolve this, I'll really appreciate it.
>
> 1- I have a list of tuples like this:
> lista= [(162, 141, 3), (162, 141, 3), (162, 141, 3), (168, 141, 2), (168, 141, 2), (168, 141, 2), (201,  141, 1), (213, 141, 1), (203, 141, 1), (562, 142, 4), (562, 142, 4), (562, 142, 4), (568, 142, 2), (568, 142, 2), (568, 142, 2), (501,  142, 1), (513, 142, 1), (503, 142, 1)]
> and I want to end with a dict like this:
> {141: {1: [203, 213, 201], 2: [168, ], 3: [162, ]}, 142: {1: [503, 513, 501], 2: [568, ], 4: [562, ]}}


(snipped)

I think you can use, with python 2.5, defaultdict for
this.  I only have access to 2.4.4 here, so my facsimile
is:

class defaultd(dict):
    def __getitem__(self, k):
        if k not in self:
            self[k] = defaultd()
        return dict.__getitem__(self, k)

lista = [(162, 141, 3), (162, 141, 3), (162, 141, 3), (168, 141, 2),
(168, 141, 2), (168, 141, 2), (201,  141, 1), (213, 141, 1), (203,
141,
1), (562, 142, 4), (562, 142, 4), (562, 142, 4), (568, 142, 2), (568,
142, 2), (568, 142, 2), (501,  142, 1), (513, 142, 1), (503, 142, 1)]

dd = defaultd()

for value, outerkey, innerkey in lista:
    li = dd[outerkey].setdefault(innerkey, [])
    if value not in li:
        li.insert(0, value)
        # or, li.append(value) if you want to reverse order

print dd

I happen to like the "autovivification" feature
found in perl and was pleased to see defaultdict in
python 2.5.  OTOH, python programmers more experienced
than I might see this and run away screaming.


--
Hope this helps,
Steven




More information about the Python-list mailing list