tags:

views:

98

answers:

2

I want to create a Python dictionary which holds values in a multidimensional accept and it should be able to expand, this is the structure that the values should be stored :-

userdata = {'data':[{'username':'Ronny Leech','age':'22','country':'Siberia'},{'username':'Cronulla James','age':'34','country':'USA'}]}

Lets say I want to add another user

def user_list():
     users = []
     for i in xrange(5, 0, -1):
       lonlatuser.append(('username','%s %s' % firstn, lastn))
       lonlatuser.append(('age',age))
       lonlatuser.append(('country',country))
     return dict(user)

This will only returns a dictionary with a single value in it (since the key names are same values will overwritten).So how do I append a set of values to this dictionary.

Note: assume age, firstn, lastn and country are dynamically generated.

Thanks.

+3  A: 
userdata = { "data":[]}

def fil_userdata():
  for i in xrange(0,5):
    user = {}
    user["name"]=...
    user["age"]=...
    user["country"]=...
    add_user(user)

def add_user(user):
  userdata["data"].append(user)

or shorter:

def gen_user():
  return {"name":"foo", "age":22}

userdata = {"data": [gen_user() for i in xrange(0,5)]}

# or fill separated from declaration so you can fill later
userdata ={"data":None} # None: not initialized
userdata["data"]=[gen_user() for i in xrange(0,5)]
extraneon
I used it within a single function, stacked up as a single unit so then I can re-use it. Thanks.
MMRUser
+1  A: 

What's the purpose of the outer data dict?

One possibility is not to use username as a key, but rather the username itself.

It seems like you are trying to use dicts as a database, but I'm not sure it's a good fit.

Andrew Jaffe