Python Forum

Full Version: how can i create a dictionary of dictionaries from a file
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
So i need to create this dictionary(dictionary of dictionaries):

my_dict={'1':{'surname':'Musk', 'name':'Elon', 'gender': 'm','growth':183},
'2':{'surname':'Holmes', 'name':'Enola', 'gender': 'f','growth':175},
'3':{'surname':'Brown', 'name':'Lilly', 'gender': 'f','growth':178},
'4':{'surname':'Lothbrok', 'name':'Ragnar', 'gender': 'm','growth':189},
'5':{'surname':'Smith', 'name':'Adreana', 'gender': 'f','growth':173},
'6':{'surname':'Moon', 'name':'Larry', 'gender': 'm','growth':184}}

I do not understand how I can do this reading and writing from a file to my_dict. And how should I write information in the file.
As a result, I need to find out how to write this information to a file and then how to write it to my_dict.
the easiest would be to read/write json file. But a csv file would do as well (i.e. using csv.DcitReader and csv.DictWriter.
What is your input data?
Json-Data looks like your example.

For example, this is csv:
surname,name,gender,growth
Musk,Elon,m,183
Holmes,Enola,f,175
Brown,Lilly,f,178
Lothbrok,Ragnar,m,189
Smith,Adreana,f,173
Moon,Larry,m,184
Example to open the csv file:
import csv

rows = []
with open("your_file.csv", encoding="utf8", newline="") as fd:
    for row in csv.DictReader(fd):
        print(row)
        rows.append(row) # adding the dict to rows
Keep in mind that everything from csv-reader is a str.
All decimals and integers are str objects. To use them for sorting or to make calculations with them,
you need to cast the str to int or float.

import csv

rows = []
with open("your_file.csv", encoding="utf8", newline="") as fd:
    for row in csv.DictReader(fd):
        row["growth"] = int(row["growth"]) # str -> int
        print(row)
        rows.append(row) # adding the dict to rows
The other question is: From where are the student numbers (which are also str in your example)?