oakca
oakca

Reputation: 1568

Getting a value of a python dict

I am getting a syntax error while trying to index a python dict:

(Pdb) o_model.flows
{(<oemof.solph.network.Bus object at 0x7f3e9c6b3ea8>, <oemof.solph.network.Transformer object at 0x7f3e9c52ce08>): <oemof.solph.network.Flow object at 0x7f3e9c50d5f8>}

Here is the key of the dict.:

(Pdb) o_model.flows.keys()
dict_keys([(<oemof.solph.network.Bus object at 0x7f3e9c6b3ea8>, <oemof.solph.network.Transformer object at 0x7f3e9c52ce08>)])

So what I am assuming is the key of the dict is (<oemof.solph.network.Bus object at 0x7f3e9c6b3ea8>, <oemof.solph.network.Transformer object at 0x7f3e9c52ce08>)

Problem is that I get an syntax error, while trying to index the o_model.flows with the key, which is mentioned above.

Normally I was expecting to get the value(<oemof.solph.network.Flow object at 0x7f3e9c50d5f8>) of the dict via, but instead I get an syntax error:

(Pdb) o_model.flows[(<oemof.solph.network.Bus object at 0x7f3e9c6b3ea8>, <oemof.solph.network.Transformer object at 0x7f3e9c52ce08>)]
*** SyntaxError: invalid syntax

What I do wrong?

Some Extras:

(Pdb) type(o_model.flows)
<class 'dict'>

Upvotes: 1

Views: 283

Answers (1)

gustavovelascoh
gustavovelascoh

Reputation: 1228

Your key is a tuple of two objects (Bus, Transformer), so in order to index it, I suppose you have to store that tuple somewhere when that dictionary is created in order to access it later or to extract the key. You can use this:

my_key = list(o_model.flows.keys())[0]
print(o_model.flows[my_key])

Example:

test = {("qwe","zxc"): [4,5,6]}
print(test.keys()) # dict_keys([('qwe', 'zxc')])
my_key = list(testprint(.keys())[0]
print(flow[my_key]) # [4 5 6]
  • Why can't just type (<oemof.solph.network.Bus object at 0x7f3e9c6b3ea8>, <oemof.solph.network.Transformer object at 0x7f3e9c52ce08>) as key?

Because that is just the human-readable representation of that objects given that there is no string assigned for printing. Common keys, as strings, are also objects at certain location e.g. (<str object at 0x7f45f4f52c36>), but its bytes are intended to be interpreted as characters when printed.

So you don't use what is printed for indexing, you should use the object itself.

Example:

class ObjNoStr():
    def __init__(self, x):
        self.x = x

class ObjStr():
    def __init__(self, x):
        self.x = x

    def __str__(self):
        return "I have x: %d" % self.x

o1 = ObjNoStr(3)
o2 = ObjStr(3)
print(o1) # <__main__.ObjNoStr object at 0x7f36d38469b0>
print(o2) # I have x: 3

Upvotes: 2

Related Questions