1

How can I create Dynamic size Multidimensional array in python?

Aim is to create a dynamic size arrays within arrays, e.g.:

ExampleArray{
   book1 : { key:val }
   book2 : { key:val }
}

This returns an error:

ExampleArray = {}
ExampleArray['book1']['key'] = 'val';

Why?

2 Answers 2

1

replace by

ExampleArray = {}
ExampleArray['book1'] = {}
ExampleArray['book1']['key'] = 'val'

when you do ExampleArray['book1'] you are trying to access it but no to affect it, therefore since the key does not exists it throws an exception

you have to affect a value to ExampleArray['book1'] (in this case dict())

PS. loose the ; at the end of the lines. you are not doing C or C++

Sign up to request clarification or add additional context in comments.

Comments

0

https://docs.python.org/3/library/collections.html#collections.defaultdict

from collections import defaultdict

ExampleArray = defaultdict(dict)

ExampleArray['book1']['key'] = 'val'

print(ExampleArray) # defaultdict(<class 'dict'>, {'book1': {'key': 'val'}})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.