2

I am learning Python now. Before I am working with Perl. In Perl we have multi-level hashes for sorting the data. Are there any types like that available in Python?

For example

$hash{$date}{$Origin_Type}++;

and

$var = {
    '2016-04-08' => {
        GSM  => 32,
        SMPP => 29
    }
}
Borodin
  • 126,100
  • 9
  • 70
  • 144
Ravi Shanker Reddy
  • 475
  • 1
  • 6
  • 21
  • They are called dictionaries - [link](http://stackoverflow.com/questions/1024847/add-key-to-a-dictionary-in-python) – LaintalAy Apr 13 '16 at 13:20
  • 3
    **Don't write perl in python. Which is a special case of "Don't line lang-A in lang-B". Because that way you will only get to know stuff from lang-B you already had in lang-A and are starting to miss.** If you are going to write python, write it in python. Read the docs. The data structure is `dict` by the way. – C Panda Apr 13 '16 at 13:33

1 Answers1

4

You can use Python dictionaries. They are hash tables like Perl hashes.

var = {'2016-04-08': {'GSM': 32, 'SMPP': 29}}
>>> var['2016-04-08']
{'SMPP': 29, 'GSM': 32}
>>> var['2016-04-08']['SMPP']
29

Note that when iterating over a Python dictionary, just like when iterating over a Perl hash, the order in which you visit the elements is unrelated to the order in which they were inserted.

ikegami
  • 367,544
  • 15
  • 269
  • 518
th3an0maly
  • 3,360
  • 8
  • 33
  • 54
  • 1
    *"Note that the order is not preserved in a dictionary"* I am surprised that I read this so often. Order isn't preserved in arrays either. Think about what you mean by *preserving an order*. – Borodin Apr 13 '16 at 13:49
  • 1
    I mean insertion order. e.g. `list.append(value)` will append it to the end. There is no equivalent in `dict`. I don't understand the mistake. Please explain? :) – th3an0maly Apr 13 '16 at 16:33
  • userdict = {} for line in str: array = line.split('|', ) system_id = array[55] Origin = array[12] if array[55] != "": userdict[Origin][system_id] += 1; I written my program like this. But Its showing error. I dont know whats the input in the file(To initialize). But I want to calculate How many System_id are present and whats the count per each system_id under that origin – Ravi Shanker Reddy Apr 14 '16 at 03:06