在Python中创建动态和可扩展的字典

25 投票
6 回答
137294 浏览
提问于 2025-04-15 20:33

我想创建一个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)

这样做只会返回一个字典,里面只有一个值(因为键名相同,值会被覆盖)。那么我该如何将一组值添加到这个字典里呢?

注意:假设agefirstnlastncountry是动态生成的。

6 个回答

11

你可以先创建一个键的列表,然后通过遍历这些键,把值存储到字典里。

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'}
14

我觉得这个问题的答案可能有点晚了,不过我还是希望能帮助到将来的某个人,所以我来给个答案。假设我有一个列表,我想把它变成一个字典。在每个子列表中,第一个元素是键,第二个元素是值。我想动态地存储这些键值对。下面是一个例子:

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

撰写回答