Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/333.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
字典的python列表追加与扩展_Python_List_Dictionary - Fatal编程技术网

字典的python列表追加与扩展

字典的python列表追加与扩展,python,list,dictionary,Python,List,Dictionary,我对python的append和extend在一个应该包含字典的列表中的用法有些困惑: holder = [] element = {} element["id"] = 1 element["value"] = 2 holder.append(element) print(holder) 按预期打印[{'id':1,'value':2}] 但是,如果我使用:holder.extend(element)而不是holder.append(element)则输出将是:['id','value

我对python的
append
extend
在一个应该包含字典的列表中的用法有些困惑:

holder = []

element = {}

element["id"] = 1
element["value"] = 2

holder.append(element)

print(holder)
按预期打印
[{'id':1,'value':2}]

但是,如果我使用:
holder.extend(element)
而不是
holder.append(element)
则输出将是:
['id','value']

有人能解释一下为什么吗?(不适用于此)

list.extend()
接受iterable并附加iterable的所有元素。默认情况下,Dictionary会迭代其键,因此所有键都会附加到列表中

list.append()
按原样获取对象并将其添加到列表中,这正是代码中发生的情况。

list.extend()
获取iterable并附加iterable的所有元素。默认情况下,Dictionary会迭代其键,因此所有键都会附加到列表中


list.append()
按原样将对象添加到列表中,这正是代码中发生的事情。

执行
append
,它会添加一个东西
元素
,即字典。
如果
元素
是一个列表,则执行
扩展
,添加
元素
的每一项:

>>> element = {}
>>> element["id"] = 1
>>> element["value"] = 2
>>> list(element)
['id', 'value']

对于dictionary,它在键上进行迭代。

执行
追加
,它添加一个thing
元素
,即dictionary。
如果
元素
是一个列表,则执行
扩展
,添加
元素
的每一项:

>>> element = {}
>>> element["id"] = 1
>>> element["value"] = 2
>>> list(element)
['id', 'value']

对于dictionary,它在键上进行迭代。

因为迭代dictionary会生成键,而不是
键值
对。试试
list(element)
这个问题绝对适用于这个-Try
holder.extend([{1:'foo'},{2:'bar'}])
。您只是对正在迭代的内容感到困惑。@jonrsharpe是的,确实感到困惑。。。现在有点清楚了,因为迭代字典生成键,而不是
键值
对。试试
list(element)
这个问题绝对适用于这个-Try
holder.extend([{1:'foo'},{2:'bar'}])
。您只是对正在迭代的内容感到困惑。@jonrsharpe是的,确实感到困惑。。。现在更清楚了