Mylies
Mylies

Reputation: 446

How to organize list of string file names into a readable form?

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

Answers (2)

Lucian Marin
Lucian Marin

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

seldomspeechless
seldomspeechless

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

Related Questions