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)
`
2
  • Tell us what happens when you try to run this. I see that you try to access tmp[4] and tmp[5] but you only expect tmp to have 4 elements. Commented Oct 28, 2017 at 2:12
  • sorry, you are right about it ! i didn't put all text values, my bad Commented Oct 28, 2017 at 4:05

3 Answers 3

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
Sign up to request clarification or add additional context in comments.

2 Comments

Also the proper split(",") for each line. Usually file.read().splitlines() is more handy to create a list.
@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
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'}

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.