Feb-17-2020, 08:22 AM
I said namedtuple, not tuple. For example
population.csv
In the last two snippets, if you just print city, the namedtuple is more readble than dhe dict
https://bugs.python.org/issue1818
But not sure what the current state is
Also instead of returning list/tuple from function, it is better to return namedtuple instead
Overall, using namedtuple instead of just tuple/list makes the element access and code readability better
population.csv
Output:name,state,population
New York City,NY,8601186
Los Angeles,CA,4057841
Chicago,IL,2679044
Houston,TX,2359480
Phoenix,AZ,1711356
Philadelphia,PA,1576596
San Antonio,TX,1565929
San Diego,CA,1453775
Compare 4 snippetsimport csv from collections import namedtuple with open('population.csv') as f: next(f) # skip header for line in f: line = line.strip().split(',') print(f'Population of {line[0]}, {line[1]} is {line[2]}') with open('population.csv', newline='') as f: rdr = csv.reader(f) next(rdr) # skip header for line in rdr: print(f'Population of {line[0]}, {line[1]} is {line[2]}') with open('population.csv', newline='') as f: rdr = csv.DictReader(f) for city in rdr: print(f"Population of {city['name']}, {city['state']} is {city['population']}") City = namedtuple('City', 'name state population') with open('population.csv', newline='') as f: rdr = csv.DictReader(f) for record in rdr: city = City(**record) print(f"Population of {city.name}, {city.state} is {city.population}")This is very basic example (assuming no suitable custom class to use), but you get the idea. Imagine, you are not just printing elements.
In the last two snippets, if you just print city, the namedtuple is more readble than dhe dict
Output:OrderedDict([('name', 'Los Angeles'), ('state', 'CA'), ('population', '4057841')])
vsOutput:City(name='New York City', state='NY', population='8601186')
There is discussion about enhancement to csv module, to have a reader that returns nameduples, not dicts.https://bugs.python.org/issue1818
But not sure what the current state is
Also instead of returning list/tuple from function, it is better to return namedtuple instead
Overall, using namedtuple instead of just tuple/list makes the element access and code readability better
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs