Reputation: 446
Im making a script to anaylze file size changes over time and at the end I have a file that looks like this
{
"path/to/file" : 10,
"second/path" : 20,
"path/to/file/spefici" : 10,
"second/path/to/" : 20,
"path/to/file/spefici/file.txt" : 10
"second/path/to/file.txt" : 20
}
But thats pretty hard to read and figure out what files change and what directories changed the most. How can I organize this dict so it looks more like this
{
"path/to/file" : 10,
"path/to/file/specific" : 10,
"path/to/file/specific/file.txt" : 10
"second/path" : 20,
"second/path/to/" : 20,
"second/path/to/file.txt" : 20
}
Upvotes: 1
Views: 72
Reputation: 194
data = {
"path/to/file" : 10,
"second/path" : 20,
"path/to/file/spefici" : 10,
"second/path/to/" : 20,
"path/to/file/spefici/file.txt" : 10,
"second/path/to/file.txt" : 20
}
sorted_data = {k: v for k, v in sorted(data.items())}
print(sorted_data)
Using dictionary comprehension it will print:
{
'path/to/file': 10,
'path/to/file/spefici': 10,
'path/to/file/spefici/file.txt': 10,
'second/path': 20,
'second/path/to/': 20,
'second/path/to/file.txt': 20
}
Upvotes: 2
Reputation: 174
I wouldn't use a dictionary here since you don't sort json or dictionaries in general.
I would make it a list and sort that.
data = {
"path/to/file" : 10,
"second/path" : 20,
"path/to/file/spefici" : 10,
"second/path/to/" : 20,
"path/to/file/spefici/file.txt" : 10
"second/path/to/file.txt" : 20
}
filelist = sorted([ [x,y] for x,y in data.items() ]) # Alphabeticly from first field
#filelist = sorted([ [x,y] for x,y in data.items() ], key=lambda x: x[1], reverse=True) # Filesize matters! Biggest first.
for file in filelist: # Present this however you want it
print(file[0],file[1])
Commented# the sorting after filesize-line since you seem to want it alphabetically after /path/file.
Upvotes: 0