0

If I have an array Numbers = [1, 2, 3] and a loop that depend on these numbers and inside the loop I have and a dictionary or some object that I want to name with the numbers in the array Numbers, how can I use the percent operand to assign the values?

So it will look like

Numbers = [1, 2, 3]
for number in Numbers:
    dictionary_"" = {}

where "" would be the number.

Just using the percent operand, something like dictionary_%g = {} %(number), will not work. How can I do this? Thanks.

1
  • Sorry I put things in the correct python format but it came out all on one line, but I think you get the picture. May 21, 2013 at 2:29

2 Answers 2

3

You can't and/or shouldn't name variables dynamically. What you can do is create a list or a dictionary that contains these three dictionaries. A two-level data structure.

numbers = [1, 2, 3]
dictionaries = {}
for number in numbers:
    dictionaries[number] = {}

Or, more compactly:

dictionaries = {number: {} for number in numbers}
2
  • 2
    I would say a list of dictionaries would be more appropriate in general (given the numeric keys), as well as closer to OP's desire.
    – jscs
    May 21, 2013 at 2:35
  • Turns out this is almost always a better idea May 21, 2013 at 2:39
2

The exec function can allow you to dynamically name variables. In your case,

Numbers = [1, 2, 3]
for number in Numbers:
    exec('dictionary_%d = {}' % number)

But this is really not a good idea. It would be helpful to know what you intend to do, but if John Kugelman's answer solves your problem I would definitely recommend that over exec.

1
  • Thanks everyone. I'll try to post a more specific example once I better identify the problem. May 21, 2013 at 3:09

Not the answer you're looking for? Browse other questions tagged or ask your own question.