python将列表分配给字典返回空列表

时间:2012-10-24 09:23:12

标签: python list dictionary

我有一个问题,我的列表frameChain被反映为空([])。 frameChain实际上是一个列表,例如:['C Level', 'Medium Term']

jsonOut[x]= {'TEXT' : node.attrib['TEXT'],
             'ID': node.attrib['ID'],
             'Sessions' : frameChain,}

我在我定义的函数之外尝试了这个,它似乎工作得很好。关于为什么这会有所不同的任何想法?

x只是一个表示外部字典索引的计数器。

1 个答案:

答案 0 :(得分:0)

根据您的评论,您可能在将列表添加到词典后修改列表。在python中,几乎所有东西,例如。变量名,列表项,字典项等只是引用值,本身不包含它们。列表是可变的,因此如果您将一个添加到字典中,然后通过另一个名称修改列表,则更改也会显示在字典中。

那是:

# Both names refer to the same list
a = [1]
b = a    # make B refer to the same list than A
a[0] = 2 # modify the list that both A and B now refer to
print a  # prints: [2]
print b  # prints: [2]

# The value in the dictionary refers to the same list as A
a = [1]
b = {'key': a}
a[0] = 2
print a # prints: [2]
print b # prints: {'key': [2]}

但是,请注意,为变量指定新值不会更改引用值:

# Names refer to different lists
a = [1]
b = a   # make B refer to the same list than A
a = [2] # make A refer to a new list
print a # prints [2]
print b # prints [1]

您创建了一个新列表,并将“手动”项从旧列表逐个复制到新列表。这是有效的,但它占用了大量的空间,并且通过使用切片有一种更简单的方法。切片返回一个新列表,所以如果你没有指定开始和结束位置,即。通过编写list_variable[:],它基本上只返回原始列表的副本。

即修改原始示例:

# Names refer to different lists
a = [1]
b = a[:] # make B refer to a copy of the list that A refers to
a[0] = 2
print a  # prints: [2]
print b  # prints: [1]

# The value in the dictionary refers to a different list than A
a = [1]
b = {'key': a[:]}
a[0] = 2
print a # prints: [2]
print b # prints: {'key': [1]}