'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.
Solution 1:[1]
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]
}
"""
Solution 2:[2]
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']}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 |
