Pergunta

I am a python beginner and created a short dictionary that links capital letters as keys to 1x3 arrays as the respective values. So something similar to this:

dict = {'A': array([1, 2, 3]), 'B': array([2.1, 3.2, 4]), etc. }

As part of my program I need to assign the key to the value as a function. But instead of writing:

A = array([1, 2, 3])
B = array([2.1, 3.2, 4])
etc.

I want to find a more general, abstract, simpler code. So far I could come up with:

for i in dict:
  i = dict[i]

But this does not quite work and I am unsure why. Sorry that I can not give a better error description here, but I don't have access to my code at the moment. Any help is appreciated! Thanks in advance!

Foi útil?

Solução

In your for loop, you're assigning the keys ("A", "B", etc.) to the variable i. So, you're correct that you can access the arrays using dict[i]; however, it doesn't really make sense to assign them to i. My guess is that you want something more like A = dict[i] the first time, and B = dict[i] the second, etc. Chances are you might not need this as the dictionary gives you a nice natural way to access these arrays.

That said, there is a way to get what you want. In your loop, you can say something like:

from numpy import array
d = {'A': array([1, 2, 3]), 'B': array([2.1, 3.2, 4])}
for key, val in d.items():
    vars()[key] = val

print "A =", A
print "B =", B

This is kind of awkward though, because namespaces in python are dictionaries anyway, so you're just taking your dictionary and putting it in the dictionary that vars() gives you.

Also, as an aside, it's sort of messy (but still valid) to call your dictionary 'dict' since dict is the builtin name for the dictionary class. So you can use dict(a=0, b=1, ...) to create a dictionary, but not if you override that name with a local variable.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top