读取文本文件行并使用python创建字典 [英] read text file lines and create a dictionary using python
本文介绍了读取文本文件行并使用python创建字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我具有以下文本文件格式
I have a following text file format
Id, person, age, city
ef12, james, 23, berlin
yt34, mary, 45, pisa
rt23, john, 56, barcelona
我想生成以下种类的字典.请帮帮我.
I want to generate a dictionary of below kind. Please help me out .
{ef12: {person:'james', age:'23',city:'berlin'},
yt34: {person:'mary', age:'45',city:'pisa'},
rt23: {person:'john', age:'23',city:'barcelona'},
}
我被困在下面
`import time
import sys
def getData():
file = open('traffic.txt', 'r')
data = file.readlines()
myDic = {}
#for line in data.split('\n'):
for line in data:
tmp = line.strip().split()
#myDic[tmp[0]]= list(tmp[1])
#print(tmp[2])
myDic[tmp[0]] = {tmp[1],tmp[2],tmp[3],tmp[4],tmp[5]}
file.close()
return myDic
theNewDictionary = getData()
print(theNewDictionary)
`
推荐答案
另一种方法是从csv中读取行,并更新每一行的字典:
Another way is to read the rows from the csv and update the dictionary with each row:
dicty = {}
for row in csv.DictReader(open('a.csv')):
dicty.update({
row['Id']: {
'person': row['person'],
'age' : row['age'],
'city' : row['city']
}
})
print(dicty)
# {'ef12': {'person': 'james', 'age': '23', 'city': 'berlin'},
# 'yt34': {'person': 'mary', 'age': '45', 'city': 'pisa'},
# 'rt23': {'person': 'john', 'age': '56', 'city': 'barcelona'}}
dicty.get('ef12')
# {'age': '23', 'city': 'berlin', 'person': 'james'}
这篇关于读取文本文件行并使用python创建字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文