Python | How to create dynamic and extensible dictionaries

I want to create a Python dictionary that contains values ​​in multidimensional agreement, and it should be expandable, this is the structure in which the values ​​should be stored: -

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

Suppose 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 return a dictionary with a single value in it (since the key names will be the same values ​​will be overwritten). So how do I add a set of values ​​to this dictionary.

Note: it is assumed that age, firstn, lastn, and country are dynamically generated.

Thanks.

+6
python
source share
3 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)] 
+11
source share

What is the purpose of an external data dict?

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

You seem to be trying to use dicts as a database, but I'm not sure if this is good.

+1
source share

You can try this Python 3+

 key_ref = 'More Nested Things' my_dict = {'Nested Things': [{'name', 'thing one'}, {'name', 'thing two'}]} my_list_of_things = [{'name', 'thing three'}, {'name', 'thing four'}] try: # Try and add to the dictionary by key ref my_dict[key_ref].append(my_list_of_things) except KeyError: # Append new index to currently existing items my_dict = {**my_dict, **{key_ref: my_list_of_things}} print(my_dict) output: { 'More Nested Things': [{'name', 'thing three'}, {'name', 'thing four'}], 'Nested Things': [{'thing one', 'name'}, {'name', 'thing two'}] } 

You can use this in your definition and make it more user friendly by typing try, catching it is rather tedious

0
source share

All Articles