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.
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.
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.
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)]
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]}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With