I'm working on a text file, "creatures.txt". An example of its contents can be seen below:
Special Type A Sunflower
2016-10-12 18:10:40
Asteraceae
Ingredient in Sunflower Oil
Brought to North America by Europeans
Requires fertile and moist soil
Full sun
Pine Tree
2018-12-15 13:30:45
Pinaceae
Evergreen
Tall and long-lived
Temperate climate
Tropical Sealion
2019-01-20 12:10:05
Otariidae
Found in zoos
Likes fish
Likes balls
Likes zookeepers
Big Honey Badger
2020-06-06 10:10:25
Mustelidae
Eats anything
King of the desert
When its contents are converted to the values of a dictionary input, it ran well.
Input
def TextFileToDictionary():
dataset = []
with open(FinalFilePath, "r") as textfile:
sections = textfile.read().split("\n\n")
for section in sections:
lines = section.split("\n")
dataset.append({
"Name": lines[0],
"Date": lines[1],
"Information": lines[2:]
})
return dataset
TextFileToDictionary()
Output
[{'Name': 'Special Type A Sunflower',
'Date': '2016-10-12 18:10:40',
'Information': ['Asteraceae',
'Ingredient in Sunflower Oil',
'Brought to North America by Europeans',
'Requires fertile and moist soil',
'Full sun']},
{'Name': 'Pine Tree',
'Date': '2018-12-15 13:30:45',
'Information': ['Pinaceae',
'Evergreen',
'Tall and long-lived',
'Temperate climate']},
{'Name': 'Tropical Sealion',
'Date': '2019-01-20 12:10:05',
'Information': ['Otariidae',
'Found in zoos',
'Likes fish',
'Likes balls',
'Likes zookeepers']},
{'Name': 'Big Honey Badger',
'Date': '2020-06-06 10:10:25',
'Information': ['Mustelidae', 'Eats anything', 'King of the desert']}]
As observed, the output comprises multiple dictionaries, without names.
Currently, I'm trying to create functions which will sort dictionaries by
1) 1st key value by alphabetical order and
2) 2nd key value by latest date.
My progress is at:
import itertools
import os
MyFilePath = os.getcwd()
ActualFile = "creatures.txt"
FinalFilePath = os.path.join(MyFilePath, ActualFile)
def TextFileToDictionaryName():
dataset = []
with open(FinalFilePath, "r") as textfile:
sections = textfile.read().split("\n\n")
for section in sections:
lines = section.split("\n")
dataset.append({
"Name": lines[0],
"Date": lines[1],
"Information": lines[2:]
})
dataset.sort(key=lambda x: x[0]['Name'], reverse=False)
return dataset
TextFileToDictionaryName()
def TextFileToDictionaryDate():
dataset = []
with open(FinalFilePath, "r") as textfile:
sections = textfile.read().split("\n\n")
for section in sections:
lines = section.split("\n")
dataset.append({
"Name": lines[0],
"Date": lines[1],
"Information": lines[2:]
})
dataset.sort(key=lambda x: x[1]['Date'], reverse=True)
return dataset
TextFileToDictionaryDate()
However, I have encountered an error "KeyError: 0". I am unsure how to resolve it.
I am also unsure as to converting the dictionary output back into string format, like in the "creatures.txt" file's contents earlier.
Does anyone know how to fix the code?
Many thanks!