0

I'm asking a question similar to this, but with python 2.7 instead. I know that I'm the same asker of the question, but the answer should be different. Here's the link.

How to make a variable name without creating an array in C++?

I looked up Data Structures on the python website, but I have no idea what they're talking about. Any help or guidance appreciated!

Community
  • 1
  • 1
Ripspace
  • 551
  • 6
  • 21
  • 3
    as like your other post I find this unclear, are you talking about an associative array type of data structure like [dictionaries](http://docs.python.org/tutorial/datastructures.html#dictionaries)? – T I Jan 01 '12 at 01:05
  • It's like a unique id that I can refer to in order to create unlimited instances and check all of them automatically. – Ripspace Jan 01 '12 at 01:08

3 Answers3

3

If you are looking for a structure that is similar to std::map in C++, you should use dict. It is a dictionary, that can have any hashable object as key (a string, a tuple, an integer). For example:

x = dict()
x['a'] = 5
x[6] = MyObject()

As you can see this is more powerful than std::map, because keys might have different types and values too.

If you want to assign a class, you also can do this:

class MyClass:
    pass

x[1] = MyClass

but maybe you are interested in having an instance of this class? This also is possible (on the same dict):

x[1] = MyClass() # this creates an instance
gruszczy
  • 40,948
  • 31
  • 128
  • 181
  • You may have the answer that I'm looking for, but one more thing. Lets say I have a class that was assigned to x[1], could I do this: x[1].var = 1, or is there a different way to do that? – Ripspace Jan 01 '12 at 01:16
  • I was more interested in instantiating a class. Thanks! – Ripspace Jan 01 '12 at 01:26
  • Actually assigning a class as a value in dict is pretty cool too, but I can't image the usage at the moment ;-) – gruszczy Jan 01 '12 at 01:27
1

In general the data structure you are looking for is a key-value mapping. Depending on language or library the name for this structure will likely be on of the following: dictionary, hash table, associative array, hash. Those are the common names though.

In python they are called dictionaries. And are created with {}. Whereas a list in python would be created with [].

A basic example would be this:

a={}
a[5]='a'
a[3]=0
print a
Output: {3: 0, 5: 'a'}
Evan
  • 6,151
  • 1
  • 26
  • 43
-6

You could do something like the following:

globals()['foo'] = 10

or

locals()['foo'] = 10

And then you can access foo by its name after that. From your other question, it seems like your asking how do you make an array (in Python, it's usually a list) without using square brackets.

Unlike C/C++, you do not need to declare the type of a Python variable, so you can do something like:

foo = []

or

foo = list()

Where the variable named 'foo' references a value with a list (like an array) type.

Peter Goodman
  • 438
  • 3
  • 12