Dictionary of lists of dictionaries in python

I am a perl script working in python and need to know a way to make the following perl in python.

$Hash{$key1}[$index_value]{$key2} = $value;

      

I saw a stackoverflow question here: List of dictionaries, in a dictionary - in Python

I still don't understand what does self.rules

or works for my solution.

My data will come from files and I will use regular expressions to capture into temporary variables until they are stored in the data structure. If you have to ask, the order associated with $index_value

is important and would like to be maintained as an integer.

Any suggestions are greatly appreciated, or if you think I need to rethink data structures with Python, that would be helpful.

+3


source to share


2 answers


You want it to h

be a dictionary ( h

because it hash

is built in Python):

h = {}

      

Now h[key]

should be a list (for some suitable one key

):

key = 'key'
L = h[key] = []

      

I have set L

to denote h[key]

to make the following explanation easier.

Now each element L

is a dictionary:

value1 = {'key2': 42, 'key3': 6*9}
L.append(value1)
value2 = {'key3': 'some other value'}
L.append(value2)

      



Now you can index the h

way you want:

h[key][0]['key2']
h[key][1]['key3']

      

You can add to the list:

h[key].append({})

      

and etc.

Is this what you want?

+1


source


Direct Python equivalent:

$Hash{$key1}[$index_value]{$key2} = $value;

      

:



Hash[key1][index_value][key2] = value

      

Unfortunately, in Python, unlike Perl, this won't work if key1

it doesn't already exist in Hash

or when index_value

it's out of range Hash[key1]

. To handle both of these cases, you need to do something like:

lst1 = Hash.setdefault(key1, [])
if index_value >= len(lst1):
    for _ in range(len(lst1), index_value+1):
        lst1.append({})
lst1[index_value][key2] = value

      

+1


source







All Articles