1

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"

superface
  • 73
  • 6
  • 1
    This may help you out, if you haven't seen it already: https://wiki.python.org/moin/HowTo/Sorting/ – ermagana Sep 17 '13 at 01:56
  • This also seems related: http://stackoverflow.com/questions/3122566 – Brian Peterson Sep 17 '13 at 02:00
  • "Python does not have native hash support like in Perl" - what are you talking about? dicts are a fundamental data type in Python. Are you looking for autovivification? You can get that with `def tree(): return collections.defaultdict(tree)`. – user2357112 Sep 17 '13 at 02:44

1 Answers1

2

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.

  • Thanks Lego Stormtroopr, the lambda you put in solved the problem. – superface Sep 17 '13 at 05:26
  • 1
    @superface If an answer helped, selecting it as an accepted answer helps answerers find unanswered questions, and show future visitors than an answer helped. –  Sep 17 '13 at 05:29