Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python | How to create dynamic and expandable dictionaries

Tags:

python

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.

like image 509
Switch Avatar asked Mar 18 '10 08:03

Switch


People also ask

How do I create a dynamic nested dictionary in Python?

To create a nested dictionary, simply pass dictionary key:value pair as keyword arguments to dict() Constructor. You can use dict() function along with the zip() function, to combine separate lists of keys and values obtained dynamically at runtime.

Can Python append dictionary?

Append values to a dictionary using the update() methodThe Python dictionary offers an update() method that allows us to append a dictionary to another dictionary. The update() method automatically overwrites the values of any existing keys with the new ones.


2 Answers

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)]
like image 105
extraneon Avatar answered Sep 29 '22 16:09

extraneon


I think it's too late for the answer but nevertheless, hoping that it may help somebody in near future I'm gonna give the answer. Let's say I have a list and I wanna make them as a dictionary. The first element of each of the sublists is the key and the second element is the value. I want to store the key value dynamically. Here is an example:

dict= {} # create an empty dictionary
list= [['a', 1], ['b', 2], ['a', 3], ['c', 4]]
#list is our input where 'a','b','c', are keys and 1,2,3,4 are values
for i in range(len(list)):
     if list[i][0] in dic.keys():# if key is present in the list, just append the value
         dic[list[i][0]].append(list[i][1])
     else:
         dic[list[i][0]]= [] # else create a empty list as value for the key
         dic[list[i][0]].append(list[i][1]) # now append the value for that key

Output:

{'a': [1, 3], 'b': [2], 'c': [4]}
like image 29
Akhilesh Pandey Avatar answered Sep 29 '22 15:09

Akhilesh Pandey