Python |如何创建动态和可扩展的词典

时间:2010-03-18 08:26:30

标签: 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)

这将只返回一个包含单个值的字典(因为键名称将覆盖相同的值)。那么如何将一组值附加到此字典中。

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

感谢。

5 个答案:

答案 0 :(得分:14)

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

答案 1 :(得分:4)

我认为答案来不及了,但是,希望它能在不久的将来对我有所帮助。假设我有一个列表,我想将它们作为字典。每个子列表的第一个元素是键,第二个元素是值。我想动态存储键值。这是一个示例:

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

输出:

{'a': [1, 3], 'b': [2], 'c': [4]}

答案 2 :(得分:2)

您可以先创建一个键列表,然后通过迭代键,可以将值存储在词典中

l=['name','age']

d = {}

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


print("Dictionary is : ",d)

输出:

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

答案 3 :(得分:1)

data字典的目的是什么?

一种可能性是不使用username作为密钥,而是使用用户名本身。

您似乎正在尝试将dicts用作数据库,但我不确定它是否合适。

答案 4 :(得分: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'}]
}

你可以在你的定义中说出这个,并使其更加用户友好,输入try catch it相当繁琐