简体   繁体   中英

How do I import text file dictionary into python dictionary

I am creating a tournament scoring system application. There are many sections to this app, for example, Participants, Team, Events and Award points. Right now I am working on the team section. I was able to create something that will allow the user to create teams. The code looks like this.

teamname = input("Team Name: ").title()
First_member = input("First Member Full Name: ").title()
if any(i.isdigit() for i in First_member):
print("Invalid Entry")
else:

There can only be 5 members in each team. This is how the data is saved

combine = '\''+teamname+'\' : \''+First_member+'\', \''+Second_member+'\', 
\''+Third_member+'\',  \''+Forth_member+'\',  \''+Fifth_member+'\'',                                  

myfile = open("teams.txt", "a+")
myfile.writelines(combine)
myfile.writelines('\n')
myfile.close()

Now If I want to remove a team how do I do that?

Apologies if you feel like i am wasting your time but still thanks for stopping by. If you want to see everything please check out this link

https://repl.it/@DaxitMahendra/pythoncode >

If text file creation is in your hand then you should just have proper YAML format of file. Your format is fairly similar to YAML.

Once you have YAML you can use PyYAML: https://pyyaml.org/wiki/PyYAMLDocumentation

This answer: YAML parsing and Python? has example of the format and how to parse as well.

you have to do a quick fix, please change your "combine" variable format to a valid "dict" format, then you can use the "ast" module, here a example

#proxy items
teamname,First_member,Second_member,Third_member,Forth_member,Fifth_member = [str(temp_name).zfill(3) for temp_name in range(6)]

#add "{" and "}" to start/end and add your values into a list "key":["value1", "value2",...]
combine = '{\''+teamname+'\' : [\''+First_member+'\', \''+Second_member+'\', \''+Third_member+'\',  \''+Forth_member+'\',  \''+Fifth_member+'\']}'

import ast
dict = ast.literal_eval(combine)
print dict.keys(), type(dict)
>>['000'] <type 'dict'>

for your case,

#change the "combine" variable
combine = '{\''+teamname+'\' : [\''+First_member+'\', \''+Second_member+'\', \''+Third_member+'\',  \''+Forth_member+'\',  \''+Fifth_member+'\']}'

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