Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
278 views
in Technique[技术] by (71.8m points)

csv - python read file (or string) into dictionary by first separator only

I need to read a file into a dictionary but it contains more than one separator:

AGE 32
JOB clerk
NAME Bob Young

should become

d = {
"AGE": "32",
"JOB": "clerk",
"NAME": "Bob Young"
}

d = pd.read_csv("file.txt", delimiter=" ", header = None).to_dict()[0] fails since NAME has a second whitespace. How can I suppress the second delimiter?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

you can read file by using native python

dicti={}
f = open("file.txt", "r").read().splitlines()
for x in f:
    dicti[x.split(' ')[0]]=x.split(' ',maxsplit=1)[1]
 
print(dicti)

and output will be:

{'AGE': '32', 'JOB': 'clerk', 'NAME': 'Bob Young'}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...