Question

I have the following dictionary in Python:

myDic = {}
myDic['username'] = 'smith44'
myDic['password'] = '123'
myDic['email'] = 'smith@gmail.com'

I want to turn this into:

username = 'smith44'
password = '123'
email = 'smith@gmail.com'

so that I can directly use username, password and email directly in one of my latter methods. I know I can use the dictionary but I need to do it this way for the sake of compatibility.

Again, what I need to do here is turn every dictionary key into a seperate attribute that will take the value of its corresponding dictionary value.

UPDATE To further support what I need to do, here is what I've done so far:

    for key, value in myDic.iteritems():
        exec("%s = " "'""%s""'" % (key, value))
Was it helpful?

Solution

If you really really need to do this:

>>> d = {}
>>> d['test'] = "foo"
>>> locals().update(d)
>>> test
'foo'

But if I were you, I'd try to find a different way of solving the problem you're trying to solve instead of automatically adding variables to your local namespace. There's almost always a way around this mess.

OTHER TIPS

you will get string in attribute = value format using str.join

In [12]: ", ".join(["%s = %s" % (k, v) for k,v in myDic.items()])
Out[12]: 'username = smith44, password = 123, email = smith@gmail.com'

In [13]: myDic.items()
Out[13]: [('username', 'smith44'), ('password', '123'), ('email', 'smith@gmail.com')]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top