1

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

}

I am stuck at below

`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)
`
scharette
  • 9,437
  • 8
  • 33
  • 67
codegeeka
  • 13
  • 1
  • 4

3 Answers3

2

You have just to add the keys

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
Simon Mengong
  • 2,625
  • 10
  • 22
  • Also the proper `split(",")` for each line. Usually `file.read().splitlines()` is more handy to create a list. – m3nda Oct 28 '17 at 02:21
  • @scharette the ouput is `{'ef12': {'person': 'james', 'age': '23', 'city': 'berlin'}, 'yt34': {'person': 'mary', 'age': '45', 'city': 'pisa'}, 'rt23': {'person': 'john', 'age': '56', 'city': 'barcelona'}}` I think it is the expected – Simon Mengong Oct 28 '17 at 02:31
1
  1. split by comma: split(',')
  2. strip after split to remove spaces: [word.strip() for word in line.split(',')]
  3. You only have 4 columns, so don't call tmp[4] and tmp[5] — it is IndexError if you do.
  4. Name your keys in the dictionary: {'person': tmp[1], 'age': tmp[2], 'city': tmp[3]}

This means:

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
aaron
  • 39,695
  • 6
  • 46
  • 102
1

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'}
aaron
  • 39,695
  • 6
  • 46
  • 102
skrubber
  • 1,095
  • 1
  • 9
  • 18