Kittystone
Kittystone

Reputation: 671

how to store value in dict correctly?

I have a code which brings AWS RDS details:

def instance_name():
    mylist=['ap-southeast-2']
    for region in mylist:
        conn=boto.rds.connect_to_region(region)
        try:
            mydb={}
            instances=conn.get_all_dbinstances()
            for instance in instances:
               #mydb.append(instance.id)
               #print instance.id
               #print instance.instance_class
               mydb['rds_name']=instance.id
               mydb['rds_type']=instance.instance_class
            return mydb
        except:
            pass

if __name__ == "__main__":
   x = instance_name()
   print x

but this only print the last RDS instance in the list.

{'rds_name': u'syd01-jumper-upgrad-shared', 'rds_type': u'db.t2.medium'}

Now if you look at the code, i have created a dictionary & want to store the rds something like this:

{
 {'rds_name': u'syd01-jumper-upgrad-shared'
          {
          'rds_type': u'db.t2.medium'
          }
 }
 {
  'rds_name': u'some_other_db'
          {
          'rds_type': u'db.t3.large'
          }
  }
}           
.
.

I.e i want my 'rds_name' to be main value and the 'rds_type' as subclass. how to do so ?

Upvotes: 0

Views: 95

Answers (2)

Jean-François Fabre
Jean-François Fabre

Reputation: 140148

you're just updating your dictionary in the loop, so you get the last value.

That said, the stucture you want to create is a set of dictionaries, which is not possible because dictionaries are not hashable (means that they cannot be converted to a hash key for a set or a dictionary key)

You want a list of dictionaries, and to do that, one line is enough using list comprehension to build your dictionaries in a list:

return [{'rds_name':instance.id,'rds_type':instance.instance_class} for instance in conn.get_all_dbinstances()]

Which is equivalent to (but faster than):

mydb = []
for instance in conn.get_all_dbinstances():
   mydb.append({'rds_name':instance.id,'rds_type':instance.instance_class})
return mydb

Aside: never do try and except: pass: you're masking all the errors that could occur, including undefined variables, etc... Let the program run, and trap exceptions only if needed and only the needed exception type(s).

Upvotes: 1

steliosbl
steliosbl

Reputation: 8921

Use a Class.

class Rds:
    def __init__(self, name, type):
        self.Name = name
        self.Type = type

Upvotes: 0

Related Questions