简体   繁体   中英

Perl to Python hash sort

I am trying to translate a line of Perl code to Python, but I came to a roadblock on Python's sorted() method. Python does not have native hash support like in Perl, so i used autodict() to replicate the hash behavior of Perl. Below is the code snippet on how the sorting was done.

Perl:

hash{one}{"index"} = 1
hash{one}{"value"} = "uno"
hash{two}{"index"} = 2
hash{two}{"value"} = "dos"
hash{three}{"index"} = 3
hash{three}{"value"} = "tres"
foreach my $ctg (sort hash{$a}{"index"} <=> hash{$b}{"index"}} keys %{ hash })

Python:

hash[one]["index"] = 1
hash[one]["value"] = "uno"
hash[two]["index"] = 2
hash[two]["value"] = "dos"
hash[three]["index"] = 3
hash[three]["value"] = "tres"
for ctg in sorted(hash):

The translation above wasn't exactly correct. The Python version is sorting based on the 1st element in the hash which is one, two, three. But the Perl version is doing sort based on "index"

First of all, your Python code doesn't run: hash isn't defined and the keys need to be strings, unless you've defined them else where.

This is probably closer to what your want, however, I can't understand the Perl in the last line.

hash = {}
hash['one']  = {"index": 1, "value": "uno"}
hash['two']  = {"index": 2, "value": "dos"}
hash['three']= {"index": 3, "value": "tres"}
for ctg in sorted(hash.keys(),key=lambda x: hash[x]['index']):
   print hash[ctg]['index'],hash[ctg]['value']

This code returns:

1 uno
2 dos
3 tres

In the sorted() function, we can define a key that indicates how we want it sorted. In your case it was being sorted by the key as thats what an iterator over a hash returns, however we have explicitly declared a sorting over the dict's keys and then a sorting key based on a value in that dict.

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