开发者

Python | How to create dynamic and expandable dictionaries

开发者 https://www.devze.com 2022-12-23 13:50 出处:网络
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 :-

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 Jame开发者_StackOverflows','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.


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]}


You can create a list of keys first and by iterating keys, you can store values in the dictionary

l=['name','age']

d = {}

for i in l:
    k = input("Enter Name of key")
    d[i]=k   


print("Dictionary is : ",d)

output :

Enter Name of key kanan
Enter Name of key34
Dictionary is :  {'name': 'kanan', 'age': '34'}


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.


You could 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 could rap this in your on definition and make it more user friendly, typing try catch it fairly tedious

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号