how to extract a text file into a dictionary

后端 未结 3 1552
自闭症患者
自闭症患者 2021-01-14 08:08

i am wondering how you would extract a text into dictionary in python. the text file is formatted as such(see below) and extract in way so that object earth for example is t

3条回答
  •  被撕碎了的回忆
    2021-01-14 09:09

    Assuming you want elements with comma-separated values as lists, try:

    mydict={}
    with open(my_file,'r') as the_file:
        for line in the_file:
            if not line.strip(): continue # skip blank lines
            key,val=line.split(": ")
            val = val.split(",")
            mydict[key] = val if len(val) > 1 else val[0]
    

提交回复
热议问题