TangerCity
TangerCity

Reputation: 855

How to make a dictionary from a file?

I have the following file (tab delimited):

ID  Name    Abbr    Disctrict
*data*
1   Newcastle   NC  AA,BB,CC
2   Manchester  MCR AA,DD,FF
3   Liverpool   LV  FF,GG,HH

Im trying to place index[1] as key and index[3] as values inside a dictionary. It doesnt seem to work yet.

my_dict = {}

path = (r'c:\data\GG\Desktop\Extra\UK_test_cities.txt')

with open(path, 'r') as f:
    for line in f:
        (key, val) = line.split()
        my_dict[int(key)] = val

This is my output:

  File "c:/data/GG/Desktop/Extra/test_1.py", line 17, in <module>
    (key, val) = line.split()
ValueError: too many values to unpack (expected 2)

This is my desired output:

my_dict = {'Newcastle': ['AA,BB,CC'],
           'Manchester': ['AA,DD,FF'],
           'Liverpool': ['FF,GG,HH']}

Upvotes: 1

Views: 72

Answers (2)

buran
buran

Reputation: 14273

my_dict = {}
path = r'c:\data\GG\Desktop\Extra\UK_test_cities.txt'
with open(path, 'r') as f:
    for _ in range(2): # skip first 2 lines
        next(f)
    for line in f:
        idx, name, abbr, district = line.split('\t')
        my_dict[name] = district.strip().split(',')

print(my_dict)

Alternatively, you can use csv module or pandas.

import pandas as pd
path = r'c:\data\GG\Desktop\Extra\UK_test_cities.txt'
df = pd.read_csv(path, sep='\t', skiprows=2, index_col='Name',
                 usecols=[1, 3], names=['Name', 'District'])
df['District'] = df['District'].str.split(',')
my_dict = df.T.to_dict('index')['District']
print(my_dict)
print(my_dict)

Both snippets will produce

{'Newcastle': ['AA', 'BB', 'CC'], 'Manchester': ['AA', 'DD', 'FF'], 'Liverpool': ['FF', 'GG', 'HH']}

Upvotes: 1

Sadegh Ranjbar
Sadegh Ranjbar

Reputation: 186

there is 4 column in each line


from collections import defaultdict 

path = (r'c:\data\GG\Desktop\Extra\UK_test_cities.txt')
my_dict=defaultdict()

with open(path, 'r') as f:
    content = f.readlines()
for line in content[2:]: #First two line does not contain data
    _,key,_,val = line.split()
    my_dict[key] = val

Upvotes: 2

Related Questions