2010-03-18 93 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'}] 
} 

你可以在你的定義說唱本,使之更加人性化,打字嘗試捕捉它相當繁瑣