-3

In Perl you can do stuff like this:

my $data->[texts}->{text1} = "hey";
print data->{texts}->{text1};

and it will print "hey". It is like a data structure (sort of array) inside another data structure...

Obviously this is possible in Python:

data = { 'jack': 4098, 'sape': 4139 }
print data['jack'];

But I want something like: data['texts']['text1'] like it was done in Perl.

And I need to be able to easily remove and add to this structure...

Help?

prestotron
  • 35
  • 1
  • 7

2 Answers2

0

You are using dict object here. It can store any type of elements you want, including another dict object.

That means, you can initialize your data like:

data = {'jack': {'age': 20, 
                 'gender': 'M'
                }, 

        'sape': {'age': 35, 
                 'gender': 'F'
                } 
       }

And then refer to it's internal values:

print(data['jack']['age'] # prints "20"
Jezor
  • 3,253
  • 2
  • 19
  • 43
-2

The bellow code describes your required data structure

code:

rec = {'name': {'first': 'Bob', 'last': 'Smith'},
                  'job': ['dev', 'mgr'],
                  'age': 40.5}

rec['name'] # 'Name' is a nested dictionary
{'last': 'Smith', 'first': 'Bob'}

rec['name']['last'] # Index the nested dictionary
'Smith'

 rec['job'] # 'Job' is a nested list
['dev', 'mgr']

 rec['job'][-1] # Index the nested list
'mgr'

 rec['job'].append('janitor') # Expand Bob's job description in-place

 rec
{'age': 40.5, 'job': ['dev', 'mgr', 'janitor'], 'name': {'last': 'Smith', 'first':
'Bob'}}

Reference https://bdhacker.wordpress.com/2010/02/27/python-tutorial-dictionaries-key-value-pair-maps-basics/

Arijit Panda
  • 1,581
  • 2
  • 17
  • 36