Python嵌套列表中的dict元素

时间:2017-01-11 20:16:02

标签: python list dictionary

我正在尝试在共享字典中创建以下数据结构(包含多个列表的列表):

{'my123': [['TEST'],['BLA']]}

代码:

records = manager.dict({})

<within some loop>
  dictkey = "my123"
  tempval = "TEST" # as an example, gets new values with every loop
  list = []
  list.append(tempval)

  if dictkey not in records.keys():
    records[dictkey] = [list]
  else:
    records[dictkey][0].append([tempval])

dict元素'my123'中的第一个列表填充了“TEST”,但是当我第二次循环(其中tempval是“BLA”)时,列表不会嵌套。

相反,我得到了:

{'my123': [['TEST']]}

我在else语句中做错了什么?

编辑: 修改了代码,但仍未添加:

records = manager.dict({})

<within some loop>
  dictkey = "my123"
  tempval = "TEST" # as an example, gets new values with every loop
  list = []
  list.append(tempval)

  if dictkey == "my123":
    print tempval # prints new values with every loop to make sure
    if dictkey not in records.keys():
      records[dictkey] = [list]
    else:
      records[dictkey].append([list])

3 个答案:

答案 0 :(得分:1)

从最后一行删除[0]部分。字典中的值已经是一个列表。您希望将第二个列表(['BLA'])附加到。

的列表

答案 1 :(得分:1)

你快到了。您需要像这样附加列表:

records = manager.dict({})

# within some loop
  dictkey = "my123"
  tempval = "TEST" # as an example, gets new values with every loop
  temp_list = [tempval] # holds a list of value


  if dictkey not in records:
    records[dictkey] = [temp_list]
  else:
    records[dictkey].append(temp_list) # append list of value

答案 2 :(得分:0)

我找到了解决方案。看起来else语句中的append不适用于类multiprocessing.managers.DictProxy。

我修改了else语句,现在它正在运行。

records = manager.dict({})

< within some loop >
  dictkey = "my123"
  tempval = "TEST" # as an example, gets new values with every loop
  temp_list = [tempval] # holds a list of value

  if dictkey not in records:
    records[dictkey] = [temp_list]
  else:
    records[dictkey] = records.get(dictkey, []) + [temp_list]

感谢大家的帮助!