'Python Multiple key in a text file
My Data is as below:
Name: Joe
Age: 26
Property: 1 of 3
Item : Car
Make: Toyota
Model: Corolla
Year:2006
Property: 2 of 3
Item : House
Address : new Street
Cost : 20000
Property: 3 of 3
Item: Stocks
Investment: 1000
Name: Blogg
Age: 28
Property: 1 of 2
Item : Bike
BikeMake: Harley
BikeModel: IronRod
BikeYear:2018
Property: 2 of 2
Item: Stocks
Investment: 2000
I need the result to look like below:
| Name | Age | Property | Item | Make | Model | Year | Address | Cost | Investment | BikeMake | BikeMode | BikeYear |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Joe | 26 | 1 of 3 | Car | Toyota | Corolla | 2006 | ||||||
| Joe | 26 | 2 of 3 | House | new Street | 20000 | |||||||
| Joe | 26 | 3 of 3 | Stocks | 1000 | ||||||||
| Blogg | 28 | 1 of 2 | Bike | Harley | Ironrod | 2018 | ||||||
| Blogg | 26 | 3 of 3 | Stocks | 2000 |
My code is currently
for line in t:
print(line)
key, _, value = line.partition(": ")
if not value: # separator was not found
value = "NA"
if "Name" in key:
stuff[index] = {"Reference": [value]} # Always use a list as vale
current_key = index
index += 1
elif key not in stuff[current_key]: # If key does not exist
stuff[current_key][key] = [value] # Create key with value in a list.
else:
stuff[current_key][key].append(value)
My current results are being pivoted by the Name key (e.g)
| Name | Age | Property | Item | Make | Model | Year | Address | Cost | Investment | BikeMake | BikeMode | BikeYear |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Joe | 26 | 1 of 3,2 of 3,3 of 3 | Car,House,Stocks | Toyota | Corolla | 2006 | New Street | 20000 | 1000 | |||
| Blogg | 28 | 1 of 2,2 of 2 | Bike,Stocks | 2000 | Harley | IronRod | 2018 |
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
