简体   繁体   中英

Python3: sorting a list of dictionary keys

I have a list of 760 files, from which I extract 2 lines of data, which are then stored in a dictionary:

output = {'file number':data, '1':somedatain1, '2':somedatain2, ... '760':somedatain760}

NB The numbers are strings because they have been obtained by doing an os.listdir('.') in order to get a list of the filenames and splitting the string down. [I could convert this into an integer number ( using int() ) if needed]

The dictionary is then printed by creating a list of the keys and iterating:

keys = output.keys()  
for x in keys:
    print(x, '\t', output[x])

However the output is in a random order [because of the unordered nature of a dictionary, which is, I believe, an inherent property - although I don't know why this is] and it would be far more convenient if the output was in numerical order according to the file number. This, then throws up the question:

Given that my list of keys is either

1. keys = ['filename', '2', '555', '764' ... '10']

or, if i change the string of the file number to an integer:

2. keys = ['filename', 2, 555, 764 ... 10]

how do i sort my list of keys according to the numeric value of the file number if it is strings (as shown in 1. above), or if it is of mixed object types (ie 1 string and 760 integers as shown in 2 above)?

You can give the sorted() function a key:

sorted(output, key=lambda k: int(k) if k.isdigit() else float('-inf'))

This will sort strings before numbers, however. Note that there is no need to call dict.keys() ; iteration over a dictionary already yields a sequence of keys, just call sorted() directly on the dictionary.

Python 3 does not define ordering for strings when compared with numbers, so for any key that is not a digit, float('-inf') (negative infinity) is returned instead to at least put those keys at the start of the ordering.

Demo:

>>> sorted(keys, key=lambda k: int(k) if k.isdigit() else float('-inf'))
['filename', '2', '10', '555', '764']

Just add your list to another variable and then following statement you get correct output:

listofdict = [{'key': value1,'key': value2,.......}]

output = listofdict[::-1]

print(output)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM