Shailesh Patel
Shailesh Patel

Reputation: 21

Python text file into directory list

I needed help to add into directory below text file. Can anyone can help me to do it? I tried
I have data.txt like below:?

A1234 161
A1234 106
A456  185
A456  108
037   125

**Output:**
directory = {
"A1234": [161,106],
"A456": [185,108],
"037": [125],
}

Thank you in advance for your help.

Upvotes: 0

Views: 85

Answers (3)

Stijn B
Stijn B

Reputation: 360

data.txt:

A1234 161
A1234 106
A456  185
A456  108
037   125

From file to dictionary:

with open('data.txt', 'r') as file:
    data_lines = file.readlines()

directory = {}

for line in data_lines:
    a, *b = line.split()
    # convert all elements of b into integers:
    b = [int(item) for item in b]
    if directory.get(a, False):
        if isinstance(b, list):
            directory[a].extend(b)
        else:
            directory[a].append(b)
    else:
        directory[a] = list(b)

print(directory)
# {'A1234': [161, 106], 'A456': [185, 108], '037': [125]}
# prettified:
"""
{
    'A1234': [161, 106],
    'A456': [185, 108],
    '037': [125]
}
"""

Upvotes: 1

Matthew Borish
Matthew Borish

Reputation: 3086

Here's a pandas solution. First we employ read_csv() and use one or more spaces as our delimiter. We need to specify string (object) dtypes to get string values for the list items as in your output. If you want ints, you could skip the dtype argument and pandas will infer them. Next we groupby the fist column (0) and convert the values in column 1 to a list with apply. Finally, we use .to_dict to get a dictionary.

import pandas as pd 

df = pd.read_csv('dir.txt', header=None, sep=r"[ ]{1,}", dtype='object')

directory = df.groupby(0)[1].apply(list).to_dict()

output:

{'037': ['125'], 'A1234': ['161', '106'], 'A456': ['185', '108']}

Upvotes: 0

Hussain Bohra
Hussain Bohra

Reputation: 1005

Try this:

output_dict = {}
data = list(map(
    lambda a:a.strip().split(),
    open("data.csv").readlines()
))
for k,v in data:
    try:
        output_dict[k].append(v)
    except:
        output_dict[k] = [v]
output_dict

Output:

{'A1234': ['161', '106'], 'A456': ['185', '108'], '037': ['125']}

Upvotes: 0

Related Questions