【问题标题】:read text file lines and create a dictionary using python读取文本文件行并使用 python 创建字典
【发布时间】:2017-10-28 02:04:20
【问题描述】:

我有以下文本文件格式

Id,    person, age,  city
ef12,  james,  23,   berlin  
yt34,  mary,   45,   pisa  
rt23,  john,   56,   barcelona

我想生成以下类型的字典。请帮帮我。

{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)
`

【问题讨论】:

  • 告诉我们当你尝试运行它时会发生什么。我看到您尝试访问 tmp[4] 和 tmp[5] 但您只希望 tmp 有 4 个元素。
  • 对不起,你是对的!我没有输入所有文本值,我的错

标签: python dictionary text


【解决方案1】:

您只需添加键

def getData():
    file = open('traffic.txt', 'r')
    data = file.readlines()
    myDic = {}
    for line in data:
        tmp = [s.replace(' ', '') for s in line.strip().split(',')]
        myDic[tmp[0]] = {'person': tmp[1], 'age': tmp[2], 'city': tmp[3]}
    file.close()
    return myDic

【讨论】:

  • 每行也是正确的split(",")。通常file.read().splitlines() 创建列表更方便。
  • @scharette 输出是{'ef12': {'person': 'james', 'age': '23', 'city': 'berlin'}, 'yt34': {'person': 'mary', 'age': '45', 'city': 'pisa'}, 'rt23': {'person': 'john', 'age': '56', 'city': 'barcelona'}} 我认为这是预期的
【解决方案2】:

另一种方法是从 csv 中读取行并使用每一行更新字典:

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'}

【讨论】:

    【解决方案3】:
    1. split 逗号:split(',')
    2. stripsplit 之后删除空格:[word.strip() for word in line.split(',')]
    3. 你只有 4 列,所以不要调用 tmp[4]tmp[5] - 如果你这样做,那就是 IndexError
    4. 在字典中命名您的键:{'person': tmp[1], 'age': tmp[2], 'city': tmp[3]}

    这意味着:

    def getData():
        file = open('traffic.txt', 'r')
        data = file.readlines()
        myDic = {}
        for line in data:
            tmp = [word.strip() for word in line.split(',')]
            myDic[tmp[0]] = {'person': tmp[1], 'age': tmp[2], 'city': tmp[3]}
        file.close()
        return myDic
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-05
      • 2013-03-02
      • 2015-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多