如何在python字典中创建具有key和key变量的列表?

时间:2019-08-19 13:17:36

标签: python dictionary

我有一个空字典。我将键和键变量添加到该字典中。如何创建包含键和键变量的空列表?

  result = {}
  result['key'] = 20
  print(result)=  {'key': 20}

  result['key'] = []
  result2 = {}
  result['key'].append(result2)






Expected result : {'key':20 : [{'7219': '0.49954929481682875'}, {'1416': '0.48741579334133667'}

但是它来了

{'key': [{'7219': '0.49954929481682875'}, {'1416': '0.48741579334133667'}]

1 个答案:

答案 0 :(得分:0)

据我所知,您不一定要使用键“ key”保存值“ 20”,而是要使用“ 20”作为键。为了实现这一点,您的代码应类似于以下内容(注意,基本上,它阐明了每个步骤):

# save an empty list using the key int(20)

# define the key and an empty dictionary
my_key = 20
result = {}
# use the key variable as key for the dictionary and create an empty list there
result[my_key] = []

# now add the other result dictionary to this list
result2 = {
    #... some entries
}
result[my_key].append(result2)
# ... some more code

这最终会产生以下形式的字典:

{20 : [{'7219': '0.49954929481682875'}, {'1416': '0.48741579334133667'}]}

但是,这仅是我对您的问题的解释。如果我做错了事,就ping我一下。