willdanceforfun
willdanceforfun

Reputation: 11240

Turning an existing array into a multidimensional

I have a simple array I'm storing strings in.

e.g.

item['name'] = 'suchy'
item['score'] = 'such'

Now however, later in the game I'd like to add an array to this item.

In my case, isn't item[] already an array and 'name' and 'score' are they keys? I'm storing 'such' and 'suchy' as variables, but instead of storing strings, I'd like to store more arrays.

I am slightly above stupid, but this seems complex for me. How is it done with python?

Edit:

Apologies for the shortness.

In PHP, you can do something like

$myArray = array
{
    'suchy' => 'such',
    'anotherarray' => array { 'something', 'else'}
}

Later on it's fairly easy to add something to the array.

 $myArray[0][3] = 'etc'

I'm trying to work out how to do something similar with python. Thanks for the comments so far. Already learned something. Thanks!

Upvotes: 0

Views: 54

Answers (2)

idjaw
idjaw

Reputation: 26578

In Python, this:

$myArray = array
{
    'suchy' => 'such',
    'anotherarray' => array { 'something', 'else'}
}

is this:

my_dict = {
    'suchy': 'such',
    'anotherarray': ['something', 'else']
}

If you want to add something at the first level, it's simply:

my_dict['stuff'] = [1,2,3,4]

which will now make it:

my_dict = {
    'suchy': 'such',
    'anotherarray': ['something', 'else']
    'stuff': [1, 2, 3, 4]
}

If you want to update a list, let's say the list stored in 'anotherarray', you do this:

my_dict['anotherarray'].append('things')

Output of my_dict['anotherarray']

['something', 'else', 'things']

I suggest reading a tutorial on dictionaries in Python:

Documentation from official docs

Upvotes: 1

segevara
segevara

Reputation: 630

If I understood you correctly you need something like this

item = {}
item['somekey'] = ['suchy'] # you're indicate that in dictionary item you will store list so in this lit you can put anything you want later and list too
item['score'] = ['such']

than later in your game you can use it like this

item['somekey'].append([1,11,2,3,4])

or if you want to add in your dictionary new item with value equal to array you can just write this

item['newkey'] = [1,2,3,4]

Upvotes: 1

Related Questions