2

Currently I have something that looks like this:

   if width < 101:
      column_placement_0[index] = rectangles
   elif width < 201:
      column_placement_1[index] = rectangles
   elif width < 301:
       column_placement_2[index] = rectangles

... and so on.

Instead, I want to be able to just initialize a single columns array which stores dictionaries.

First, I feel that I would initialize an array normally...

columns = []

but then I don't know how I would reference the individual list and dictionary indices maybe something like a 2D array in Java?

columns[index][dict_key] = value

What do I do?

7
  • The way you have described it is exactly how you would do it. Did you run into a problem? Commented Feb 16, 2016 at 4:43
  • You're correct, just put the dict key in quotes if you type the name in. Column_placement[index]['key'] Commented Feb 16, 2016 at 4:44
  • 1
    You only put the dictionary key in quotes if the key is a string. Commented Feb 16, 2016 at 4:56
  • Are you trying to replace column_placement_0 and etc... with the single column list? It appears that 100 possible widths could go into a single column_placement_X ... except it has some index thing that has me puzzled. If two rectangles end up in the same index (is that even possible?) should one overwrite the other? If you wrote a demo script that shows what you are doing it would help. Your fragments and description leave a lot to interpretation. Commented Feb 16, 2016 at 5:18
  • If all you want to do is preallocate the list, you need to decide what you want the default value to be and then do for instance columns = [None] * 1000. Commented Feb 16, 2016 at 5:19

1 Answer 1

7

So although people said my code would work as it was the final solution ended up being:

For initialization:

columns = [{} for i in range(10)]

And to store a value:

columns[i][key] = desired value

I'm kind of surprised that people just downvoted my question. The more Python I do, the more this seems like a pretty common data structure...

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

1 Comment

I'm surprised, too. As of April 2024, this answer is still relevant.

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.