Question

I'm trying to find a way to assign independent variable names to different items in a dictionary. Problem is, all the items use the same key. I'm using PYMSSQL to query the DB Server for a list of DB names.

conn = pymssql.connect(DBServer, DBUser, DBPass, 'master')
cursor = conn.cursor(as_dict=True)
##print 'On the following prompt, please enter the SQL command you wish to execute.'
##query = raw_input(">>")
cursor.execute("""
Select name from msdb.sys.databases
""")
for row in cursor:
    print row
    print '-----------------------------'

conn.close()

This is giving me an output of:

{u'name': u'master'}
-----------------------------
{u'name': u'tempdb'}
-----------------------------
{u'name': u'model'}
-----------------------------
{u'name': u'msdb'}
-----------------------------
{u'name': u'MIADMS'}
-----------------------------
{u'name': u'Active'}
-----------------------------

As you can see, each item is under the same name key. What I'd like to do is assign each entry a specific variable, such as:

DB1 = master
DB2 = tempdb
DB3 = mode1
DB4 = msdb
etc...

My end goal, is to provide the user a choice of which DB to run further queries against.

Was it helpful?

Solution

Exactly what you asked for:

for row in enumerate(cursor):
    exec("DB{0} = row[1][u'name']".format(row[0] + 1))

This will dynamically create variables DB1, DB2, ..., DBn

But actually you probably want:

x = {"DB{0}".format(row[0] + 1): row[1][u"name"] for row in enumerate(cursor)}

which will actually create a dict with keys DB1, DB2, ..., DBn and values holding database names.

OTHER TIPS

What you want is to build up a list of the results.

names = []
for row in cursor:
    names.append(row["name"])

Note that you can do this nicely using a list comprehension:

>>> [row["name"] for row in cursor]
[u'master', u'tempdb', u'model', ...]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top