Path: csiph.com!usenet.pasdenom.info!aioe.org!news.stack.nl!newsfeed.xs4all.nl!newsfeed3.news.xs4all.nl!xs4all!post.news.xs4all.nl!not-for-mail Return-Path: X-Original-To: python-list@python.org Delivered-To: python-list@mail.python.org X-Spam-Status: OK 0.000 X-Spam-Evidence: '*H*': 1.00; '*S*': 0.00; 'skip:[ 20': 0.04; 'mrab': 0.05; 'attribute': 0.07; 'column': 0.07; '3),': 0.09; 'attributes': 0.09; 'feature.': 0.09; 'received:80.91': 0.09; 'received:80.91.229': 0.09; 'received:gmane.org': 0.09; 'received:list': 0.09; 'rows': 0.09; 'similar,': 0.09; 'try:': 0.09; 'subject:How': 0.10; 'python': 0.11; 'suggest': 0.14; '""")': 0.16; '"_")': 0.16; '"w")': 0.16; '1),': 0.16; '2),': 0.16; '4),': 0.16; 'attr': 0.16; 'collections': 0.16; 'columns': 0.16; 'csv': 0.16; 'dict': 0.16; 'first:': 0.16; 'identifiers': 0.16; 'namedtuple': 0.16; 'received:80.91.229.3': 0.16; 'received:dip0.t-ipconnect.de': 0.16; 'received:plane.gmane.org': 0.16; 'received:t-ipconnect.de': 0.16; 'shortcut': 0.16; 'subject:key': 0.16; 'subject:python': 0.16; 'so.': 0.16; 'wrote:': 0.18; 'bit': 0.19; 'module': 0.19; 'later': 0.20; 'example': 0.22; 'import': 0.22; 'header:User-Agent:1': 0.23; 'skip:i 40': 0.24; 'fine': 0.24; 'header': 0.24; 'equivalent': 0.26; 'mention': 0.26; 'posts': 0.26; 'header:X-Complaints-To:1': 0.27; "doesn't": 0.30; "i'm": 0.30; 'work.': 0.31; "skip:' 10": 0.31; 'perl': 0.31; 'class': 0.32; 'checked': 0.32; 'run': 0.32; 'minimal': 0.33; 'not.': 0.33; 'could': 0.34; 'something': 0.35; 'but': 0.35; 'european': 0.36; 'module.': 0.36; 'subject:?': 0.36; 'too': 0.37; 'skip:o 20': 0.38; 'generic': 0.38; 'to:addr:python- list': 0.38; 'sure': 0.39; 'to:addr:python.org': 0.39; 'unable': 0.39; 'skip:p 20': 0.39; 'university': 0.39; 'received:org': 0.40; 'identify': 0.61; 'address': 0.63; 'email addr:gmail.com': 0.63; 'information': 0.63; 'education': 0.64; 'more': 0.64; 'by:': 0.65; 'close': 0.67; 'below:': 0.68; 'usa': 0.69; 'skip:a 40': 0.72; 'age': 0.80; 'concept.': 0.84; 'gender': 0.91; 'migrating': 0.91; 'many,': 0.93; 'race': 0.95 X-Injected-Via-Gmane: http://gmane.org/ To: python-list@python.org From: Peter Otten <__peter__@web.de> Subject: Re: How to implement key of key in python? Date: Sat, 10 May 2014 10:21:54 +0200 Organization: None References: <1ba8744e-943b-4c71-abd7-9dea12db8780@googlegroups.com> <85c11614-b1a3-4021-b071-ffa1e0e5d3a7@googlegroups.com> Mime-Version: 1.0 Content-Type: text/plain; charset="ISO-8859-1" Content-Transfer-Encoding: 7Bit X-Gmane-NNTP-Posting-Host: p57bdb6fa.dip0.t-ipconnect.de User-Agent: KNode/4.11.5 X-BeenThere: python-list@python.org X-Mailman-Version: 2.1.15 Precedence: list List-Id: General discussion list for the Python programming language List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Newsgroups: comp.lang.python Message-ID: Lines: 120 NNTP-Posting-Host: 2001:888:2000:d::a6 X-Trace: 1399710131 news.xs4all.nl 2944 [2001:888:2000:d::a6]:57454 X-Complaints-To: abuse@xs4all.nl Xref: csiph.com comp.lang.python:71237 eckhleung@gmail.com wrote: > 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') Using a csv.DictReader comes close with minimal effort: # write demo data to make the example self-contained with open("tmp.csv", "w") as f: f.write("""\ 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 """) import csv import pprint with open("tmp.csv") as f: attr = {row["ID"]: row for row in csv.DictReader(f)} pprint.pprint(attr) print(attr["ACC499"]["age"]) The "dict comprehension" attr = {row["ID"]: row for row in csv.DictReader(f)} is a shortcut for attr = {} for row in csv.DictReader(f): attr[row["ID"]] = row If you insist on attribute access (row.age instead of row["age"]) you can use a namedtuple. This is a bit more involved: import csv import pprint from collections import namedtuple with open("tmp.csv") as f: rows = csv.reader(f) header = next(rows) # make sure column names are valid Python identifiers header = [column.replace("-", "_") for column in header] RowType = namedtuple("RowType", header) key_index = header.index("ID") attr = {row[key_index]: RowType(*row) for row in rows} pprint.pprint(attr) print(attr["ABC123"].race) > The following links mention something similar, Too many, so I checked none of them ;)