I am trying to dump/sort JSON values by a specific time format.
Before asking, I have looked as various questions such as:
- When I tried to sort a list, I got an error 'dict' object has no attribute (This was actually a problem after trying some things)
- Sorting a JSON file by a certain key (Most specific one, though I do not use any name keys)
- JSON output sorting in Python (Did not really help)
The structure of my JSON is the following:
{
"Arthur": "12/12",
"Lisa": "10/12"
}
The date format is dd/mm
. I want to have 10/12
before 12/12
in that matter. This should not however happen while reading out the JSON, but rather while dumping
the value.
The codes I tried to use:
with open(f"saved_date.json", "r", encoding='utf-8') as f:
data = json.load(f) # Just so you can see how I read out the JSON
with open('saved_date.json', 'w', encoding='utf-8') as fpp:
json.dump(data, fpp, indent=2, sort_keys=True) # Sorting the keys does not work obviously
with open('saved_date.json', 'w', encoding='utf-8') as fpp:
json.dump(sorted(data, key=lambda x: datetime.strptime(date, "%d/%m")), fpp, indent=2) # date is individually given in the format mentioned above
Maybe someone here can see what went wrong or give me tips on how to better structure it. I currently update the JSON with:
try:
data[f"{author}"] = date # author is the one using/executing the code
except:
new = {author: date}
data.update(new)
CodePudding user response:
data = {'Arthur': '12/12', 'Lisa': '10/12'}
with open('saved_date.json', 'w', encoding='utf-8') as f:
json.dump(dict(sorted(data.items(), key=lambda x: x[1])), f, indent=2)
Output:
{
"Lisa": "10/12",
"Arthur": "12/12"
}
CodePudding user response:
Because your dates are in dd/mm
format, you cannot sort them alphabetically; you need instead to sort on the mm
part, then the dd
part:
data = {'Arthur': '12/12', 'Lisa': '10/12', 'Joe': '31/05'}
json.dumps(dict(sorted(data.items(), key=lambda x: x[1].split('/')[::-1])), indent=2)
Output:
{
"Joe": "31/05",
"Lisa": "10/12",
"Arthur": "12/12"
}