-1

I have a variable such as:

x = 'HELLO'

I want to access a DIC using the following string

self.dname.x[0]

which inherenlty should mean

self.dname.HELLO[0]

what is the proper way to do this in python? What is the proper term for this type of variable?

blonc
  • 193
  • 2
  • 14

2 Answers2

1

I'm not sure to understand the question, but you might want to have a look at the getattr builtin function (https://docs.python.org/3/library/functions.html#getattr).

For example, in your case (again, if I understand correctly) :

x = 'HELLO'
getattr(self.dname, x)[0]
Trap
  • 218
  • 3
  • 8
0

Assuming self.dname is a dictionary:

self.dname[x][0]

x is an "index" variable - you are using it to find the data you want. Here's a related question going the other way.

Example: (tested in Python 2 and 3)

>>> foo={'HELLO': [1,2,3]}
>>> foo
{'HELLO': [1, 2, 3]}
>>> foo.HELLO[0]                          <--- doesn't work
AttributeError: 'dict' object has no attribute 'HELLO'
>>> x='HELLO'
>>> foo[x][0]                             <--- works fine
1

You asked about self.x. If x is a regular variable, you don't reference it with self. (as in the example above). If x is a member of your class, then yes, you will need to use self.x. However, if you are carrying around a key and a dictionary, you might consider redesigning your data structures to carry the resulting value instead.

cxw
  • 16,685
  • 2
  • 45
  • 81
  • thanks cxw - q: it seems that if self.x = 'HELLO' that means i also always need to add self.x with in the [self.x] is that proper? seems like a lot of extra work to add self every place. – blonc Apr 04 '18 at 19:38
  • @blonc Updated - let me know if this answers your question. – cxw Apr 04 '18 at 20:19
  • If x is a member of your class (self refers to the instance of that class), then yes, you will need to do that. Your given example doesn't show that, however. – Ketzak Apr 04 '18 at 20:19
  • Was directed at blonc. Forgot to throw a tag in there. – Ketzak Apr 04 '18 at 20:25