How to implement key of key in python?

MRAB python at mrabarnett.plus.com
Fri May 9 22:30:06 EDT 2014


On 2014-05-10 02:22, eckhleung at gmail.com wrote:
> I'm migrating from Perl to Python and unable to identify the equivalent of key of key concept. The following codes run well,
>
> import csv
>
> attr = {}
>
> with open('test.txt','rb') as tsvin:
>      tsvin = csv.reader(tsvin, delimiter='\t')
>
>      for row in tsvin:
>          ID = row[1]
>
>
> until:
>          attr[ID]['adm3'] = row[2]
>
> I then try:
>          attr[ID].adm3 = row[2]
>
> still doesn't work. Some posts suggest using module dict but some do not. I'm a bit confused now. Any suggestions?
>
Python doesn't have Perl's autovivication feature. If you want the
value to be a dict then you need to create that dict first:

attr[ID] = {}
attr[ID]['adm3'] = row[2]

You could also have a look at the 'defaultdict' class in the
'collections' module.



More information about the Python-list mailing list