Home > OS >  Python. csv to usable dict
Python. csv to usable dict

Time:10-16

im trying to build a dictonary form a csv-file and then to give another function this dictonary but Python forms it to some kind of object and i cant handle that with my knowledge. Output of the print is: <class 'csv.DictReader'> <csv.DictReader object at 0x00000172BBB1CCD0>

def load_cities():
"""
Read CSV-Data from File into a Dictonary.
"""
    city_dict = {}
       
    with open(CURRENT_DIR / FILE, mode = "r", encoding = "utf-8") as fin:
        city_dict = csv.DictReader(fin)
        print(type(city_dict), city_dict)

    sort_by_name(city_dict)

CodePudding user response:

csv.DictReader creates an object that operates like a regular reader but maps the information in each row to a dict whose keys are given by the optional fieldnames parameter.

How does your data looks like? If you want to get a list of dicts (for each row), you can do:

print(list(city_dict))

If you want to create one dictionary, you can create it like this

print({row[0]:row[1] for row in csv.reader(fin)})

CodePudding user response:

I had modified a solution from another problem and this worked. But can the dictReader build usable dictonaries?

def load_cities():
"""
Read CSV-Data from File into a Dictonary.
"""
    results = []

    file = open("worldcities_short.csv", mode="r", encoding="utf-8")
    cities_string = file.read()
    file.close()

    input_list = cities_string.split("\n") 
    for row in input_list:
        words = row.split(",")
        results.append(words)
    header = results.pop(0)
    city_dict = {}
    for row in results:
        first_name = row[0]
        city_dict[first_name] = dict(zip(header, row))
    print(city_dict)
  • Related