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

Swi*_*tch 11 python

我想创建一个Python字典,它在多维接受中保存值,它应该能够扩展,这是应该存储值的结构: -

userdata = {'data':[{'username':'Ronny Leech','age':'22','country':'Siberia'},{'username':'Cronulla James','age':'34','country':'USA'}]}
Run Code Online (Sandbox Code Playgroud)

让我们说我想添加另一个用户

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)
Run Code Online (Sandbox Code Playgroud)

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

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

谢谢.

ext*_*eon 18

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)
Run Code Online (Sandbox Code Playgroud)

或更短:

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)]
Run Code Online (Sandbox Code Playgroud)


小智 6

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

l=['name','age']

d = {}

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


print("Dictionary is : ",d)
Run Code Online (Sandbox Code Playgroud)

输出 :

l=['name','age']

d = {}

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


print("Dictionary is : ",d)
Run Code Online (Sandbox Code Playgroud)


小智 5

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

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
Run Code Online (Sandbox Code Playgroud)

输出:

{'a': [1, 3], 'b': [2], 'c': [4]}
Run Code Online (Sandbox Code Playgroud)