How to set contents of a file that don't start with “\t” as keys, and those who start with “\t” and end with “\n” as values to the key before them?

旧街凉风 提交于 2020-07-08 00:49:09

问题


I want make a dictionary that looks like this: { 'The Dorms': {'Public Policy' : 50, 'Physics Building' : 100, 'The Commons' : 120}, ...}

This is the list :

['The Dorms\n', '\tPublic Policy, 50\n', '\tPhysics Building, 100\n', '\tThe Commons, 120\n', 'Public Policy\n', '\tPhysics Building, 50\n', '\tThe Commons, 60\n', 'Physics Building\n', '\tThe Commons, 30\n', '\tThe Quad, 70\n', 'The Commons\n', '\tThe Quad, 15\n', '\tBiology Building, 20\n', 'The Quad\n', '\tBiology Building, 35\n', '\tMath Psych Building, 50\n', 'Biology Building\n', '\tMath Psych Building, 75\n', '\tUniversity Center, 125\n', 'Math Psych Building\n', '\tThe Stairs by Sherman, 50\n', '\tUniversity Center, 35\n', 'University Center\n', '\tEngineering Building, 75\n', '\tThe Stairs by Sherman, 25\n', 'Engineering Building\n', '\tITE, 30\n', 'The Stairs by Sherman\n', '\tITE, 50\n', 'ITE']

This is my code:

def load_map(map_file_name):
    # map_list = []
    map_dict = {}
    map_file = open(map_file_name, "r")
    map_list = map_file.readlines()
    for map in map_file:
        map_content = map.strip("\n").split(",")
        map_list.append(map_content)
    for map in map_list:
        map_dict[map[0]] = map[1:]
    print(map_dict)
if __name__ == "__main__":
    map_file_name = input("What is the map file? ")
    load_map(map_file_name)

回答1:


Since your file's content is apparently literal Python data, you should use ast.literal_eval to parse it not some ad-hoc method.

Then you can just loop around your values and process them:

def load_map(mapfile):
    with open(mapfile, encoding='utf-8') as f:
        data = ast.literal_eval(f.read())

    m = {}
    current_section = None
    for item in data:
        if not item.startswith('\t'):
            current_section = m[item.strip()] = {}
        else:
            k, v = item.split(',')
            current_section[k.strip()] = int(v.strip())
    print(m)


来源:https://stackoverflow.com/questions/61051663/how-to-set-contents-of-a-file-that-dont-start-with-t-as-keys-and-those-who

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!