我想创建一个 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
是动态生成的。
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)]
我认为现在回答为时已晚,但是,希望它能在不久的将来对某人有所帮助,我会给出答案。假设我有一个列表,我想将它们作为字典。每个子列表的第一个元素是键,第二个元素是值。我想动态存储键值。这是一个例子:
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]}
您可以先创建一个键列表,然后通过迭代键,您可以将值存储在字典中
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'}
外部
data
dict 的目的是什么?
一种可能性是不使用
username
作为密钥,而是用户名本身。
您似乎在尝试使用字典作为数据库,但我不确定它是否合适。
你可以试试这个 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 相当乏味