简体   繁体   中英

Creating a dictionary from csv file

I was given the following problem and I am a little uncertain. I understand that the dictionary contains each town and their distance from each city, but is it structured like {Albury: 925,1440,352,3937,308,3583,565......} or something different?

The following table was downloaded from the web and saved in a file distances.csv. It specifies road distances, measured in kilometres, between major towns (eg Albury), and capital cities (eg Adelaide).

Town,Adelaide,Brisbane,Canberra,Darwin,Melbourne,Perth,Sydney
Albury,925,1440,352,3937,308,3583,565
Alice Springs,1544,2998,2658,1503,2255,3549,2931
Ballarat,618,1743,777,3645,112,3309,973
Bendigo,639,1619,653,3671,147,3335,849
Broken Hill,515,1545,1108,3128,825,2824,1154
Broome,4269,4646,4975,1880,4996,2233,5112
Cairns,3384,1699,2954,2885,3055,6050,2685
...

Consider the following code, which loads the data from this file.

from csv import DictReader
def p(f):
    a = {}
    for row in DictReader(open(f)):
        x = row["Town"]
        b = {}
        for k in row:
            if k != "Town":
                 b[k] = int(row[k])
        a[x] = b
    return a

t = p("distances.csv")

Briefly explain, in 20-30 words, the data structure contained in the variable t after the code has been executed.

If you add

import pprint
pprint.pprint(t)

at the bottom of the script and execute it, you will see your data structure quite clearly. It will look something like this:

{'Albury': {'Adelaide': 925,
            'Brisbane': 1440,
            (...)
            'Sydney': 565},
 'Alice Springs': {'Adelaide': 1544,
                   (...)

But, as @sarnold said in his comment, since this smells like homework, I'll leave it to you to explain the data structure. As a hint you might want to look at the DictReader documentation for how the data is created.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM