2010-03-18 95 views
6

我想创建持有多维值的Python字典接受,它应该是能够扩大,这是值应存储结构: -Python |如何创建动态的,可扩展的字典

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

比方说,我想添加其他用户

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) 

这只会返回与一个单一值的字典(因为这些按键的名称是相同的值将覆盖)。所以我怎么一组值追加到此字典。

注意:假设年龄,firstn,lastn和country是动态生成的。

谢谢。

+0

lontatuser与列表中的用户数据关键数据?你输入字典的用户是什么? – extraneon 2010-03-18 08:32:05

回答

11
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) 

或更短:

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)] 
+0

我在一个单一的功能中使用它,作为一个单元堆叠起来,然后我可以重新使用它。谢谢。 – Switch 2010-03-18 09:16:40

1

什么是外data字典的目的是什么?

一种可能性是不使用username作为关键字,而是使用用户名本身。

看起来你正在尝试使用字典作为数据库,但我不确定它是否合适。

0

你可以试试这个 的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'}] 
} 

你可以在你的定义说唱本,使之更加人性化,打字尝试捕捉它相当繁琐