How to implement key of key in python?

eckhleung at gmail.com eckhleung at gmail.com
Fri May 9 23:28:29 EDT 2014


On Saturday, May 10, 2014 10:30:06 AM UTC+8, MRAB wrote:
> On 2014-05-10 02:22, I 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.

I identify the information below:
s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
d = defaultdict(list)
for k, v in s:
  d[k].append(v)

While it is fine for a small dataset, I need a more generic way to do so. Indeed the "test.txt" in my example contains more columns of attributes like:

ID address age gender phone-number race education ...
ABC123 Ohio, USA 18 F 800-123-456 european university
ACC499 London 33 M 800-111-400 african university
...

so later I can retrieve the information in python by:

attr['ABC123'].address (containing 'Ohio, USA')
attr['ABC123'].race (containing 'european')
attr['ACC499'].age (containing '33')

The following links mention something similar,

http://courses.cs.washington.edu/courses/cse140/13wi/csv-parsing.html
http://stackoverflow.com/questions/8800111/parse-csv-file-and-aggregate-the-values
http://stackoverflow.com/questions/17763642/reading-tab-separated-file-into-a-defaultdict-python
http://semanticbible.com/blogos/2009/06/12/reading-tab-delimited-data-in-python-with-csv/

unfortunately none of them illustrates how to store the values and access them later. Moreover, they bring some new terms, e.g. combined, [], etc.

Is there any better reference?

Thanks again!




More information about the Python-list mailing list