How to say $a=$b->{"A"} ||={} in Python?

Paul McGuire ptmcg at austin.rr.com
Thu Aug 16 22:25:03 EDT 2007


On Aug 16, 7:53 pm, beginner <zyzhu2... at gmail.com> wrote:
> On Aug 16, 6:21 pm, James Stroud <jstr... at mbi.ucla.edu> wrote:
>
>
>
>
>
> > beginner wrote:
> > > Hi All.
>
> > > I'd like to do the following in more succint code:
>
> > > if k in b:
> > >     a=b[k]
> > > else:
> > >     a={}
> > >     b[k]=a
>
> > > a['A']=1
>
> > > In perl it is just one line: $a=$b->{"A"} ||={}.
>
> > I'm afraid you've asked a non sequiter:
>
> > euler 40% cat test.pl
>
> > $a=$b->{"A"} ||={} ;
> > print "$a\n" ;
>
> > $b->{"B"} = 0 ;
> > $a=$b->{"B"} ||={} ;
> > print "$a\n" ;
>
> > $b->{"X"} = 15 ;
> > $a=$b->{"X"} ||={} ;
> > print "$a\n" ;
>
> > euler 41% perl test.pl
> > HASH(0x92662a0)
> > HASH(0x926609c)
> > 15
>
> > James
>
> > --
> > James Stroud
> > UCLA-DOE Institute for Genomics and Proteomics
> > Box 951570
> > Los Angeles, CA 90095
>
> >http://www.jamesstroud.com/
>
> It is not supposed to be used this way.
> $b is supposed to be a hash-table of hash-table. If a key exists in
> $b, it points to another hash table. The $a=$b->{"A"} ||={} pattern is
> useful when you want to add records to the double hash table.
>
> For example, if you have a series of records in the format of (K1, K2,
> V), and you want to add them to the double hash-table, you can do
> $a=$b->{K1} || ={}
> $a->{K2}=V- Hide quoted text -
>
> - Show quoted text -

I think this demonstrates the Python version of what you describe.

-- Paul

from collections import defaultdict

data = [
    ('A','B',1), ('A','C',2), ('A','D',3), ('B','A',4),
    ('B','B',5), ('B','C',6), ('B','D',7),
    ]

def defaultdictFactory():
    return defaultdict(dict)

table = defaultdict(defaultdictFactory)

for k1,k2,v in data:
    table[k1][k2] = v

for kk in sorted(table.keys()):
    print "-",kk
    for jj in sorted(table[kk].keys()):
        print "  -",jj,table[kk][jj]

prints:

- A
  - B 1
  - C 2
  - D 3
- B
  - A 4
  - B 5
  - C 6
  - D 7




More information about the Python-list mailing list