如何在python字典中创建一个包含key和key变量的列表?

2024-09-29 01:19:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一本空字典。我把键和键变量加到字典里。如何创建一个包含key和key变量的空列表?你知道吗

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

Tags: key列表字典resultexpectedprintappendresult2
2条回答

看来你需要。你知道吗

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

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

据我所知,您不一定要用“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'}]}

不过,这只是我对你问题的解释。如果我有什么不对劲,就打电话给我。你知道吗

相关问题 更多 >