dictionary idiom needed

Arnaud Delobelle arnodel at googlemail.com
Thu Dec 11 15:19:35 EST 2008


Brandon <your.master at gmail.com> writes:

> Thanks bear -
>
> Some outside advice has me looking at nested dictionaries.  But I am
> still bogged down because I've not created one before and all examples
> I can find are simple ones where they are created manually, not with
> loops.  Maybe a further example:
>
> data:
>   POS1    POS2   POS3
> ['word1','tagA','tagB']
> ['word2','tagC','tagD']
> ['word1','tagE','tagB']
> ['word1','tagC','tagF']
>
> ... and so on.  FWIW:  I am guaranteed that the set of tags that may
> occur in position2 is complementary to the set of tags that may occur
> in position3.
>
> Now I want to get an accounting of all the tags that occurred in
> position3 in the context of, say, word1.  Here I've shown that for
> word1, tagB and tagF occurs.  I want a way to access all this
> information such that nested_dict['word1']['tagB'] = 2, and nested_dict
> ['word1']['tagF'] = 1.
>
> As I mentioned, I already have dicts such that dictA['word1'] = 3, and
> dictB['tagB'] = 2.  I used defaultdict to build those, and that seems
> to be causing me to get some funky values back from my initial
> attempts to build a nested dictionary.  I am stumbling at constructing
> a "for" loop that automatically creates such nested dictionaries.
>
> I hope that clears things up.  If you still have any advice, it's much
> appreciated.
>
> Thanks,
>
> Brandon

>>> from collections import defaultdict
>>> 
>>> data = [['word1','tagA','tagB'],
...         ['word2','tagC','tagD'],
...         ['word1','tagE','tagB'],
...         ['word1','tagC','tagF']]
>>> 
>>> d = defaultdict(lambda: defaultdict(int))
>>> 
>>> for w, t1, t2 in data:
...     d[w][t2] += 1
... 
>>> d['word1']['tagB']
2
>>> d['word2']['tagD']
1
>>> d['word2']['tagF']
0

HTH

-- 
Arnaud



More information about the Python-list mailing list