Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/354.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将dict值扩展到列表_Python_Python 2.6 - Fatal编程技术网

Python将dict值扩展到列表

Python将dict值扩展到列表,python,python-2.6,Python,Python 2.6,在Python2.6中,我试图将dict值扩展到一个列表中,当我运行extend时,我并没有将所有字典值都扩展到列表中。我错过了什么 def cld_compile(ru,to_file,cld): a = list() p = subprocess.Popen(ru, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) a = p.stdout.re

在Python2.6中,我试图将dict值扩展到一个列表中,当我运行extend时,我并没有将所有字典值都扩展到列表中。我错过了什么

def cld_compile(ru,to_file,cld):
    a = list()
    p = subprocess.Popen(ru, shell=True, stdout=subprocess.PIPE,
                         stderr=subprocess.STDOUT)
    a = p.stdout.readlines()
    p.wait()
    if (p.returncode != 0):
        os.remove(to_file)
        clderr = dict()
        clderr["filename"] = cld
        clderr["errors"] = a[1]
    return clderr




def main():
    clderrors = list()
    <removed lines>
    cldterr = cld_compile(ru,to_file,cld)
    clderrors.extend(cldterr)
当我尝试将cldterr扩展到列表CLDERROR时,我只得到:

print clderrors
['errors', 'filename']

对。当您以字典的名称访问字典时,它将只对键进行迭代。如果希望字典值位于列表中,可以执行以下操作:

errList={'errors': 'fail 0[file.so: undefined symbol: Device_Assign]: library file.so\r\n', 'filename': '/users/home/ili/a.pdr'}
l= [(i +" "+ d[i]) for i in errList]
print l 
否则,您可以访问字典作为元组列表:

print errList.items()

dict.\uuuuu iter\uuuuuu
运行字典的所有键,但不给出值,因此对于以下内容:

d = {'a':1, 'b':2, 'c':3}
for element in d:
    print(element)
# "a"
# "b"
# "c"
这就是为什么
list.extend
只提供键
“errors”
“filename”
。你想给你什么,是更好的问题?我甚至不知道该如何工作——可能是
(键、值)
的元组?为此,请访问
dict.items()
,它将为您提供一个
dict\u items
对象,该对象生成
(键,值)
每次迭代:

使用相同的示例:

for element in d.items():
    print(element)
# ("a",1)
# ("b",2)
# ("c",3)
或者在您的情况下:

for key,value in cldterr.items():
    clderrors.append((key,value))

# or if you want future programmers to yell at you:
# [clderrors.append(key,value) for key,value in cldterr.items()]
# don't use list comps for their side effects! :)
或者简单地说:

clderrors.extend(cldterr.items())

这是因为
.extend()
需要一个序列,而要使用
append()
需要一个对象

比如说

>>> l = list()
>>> d = dict('a':1, 'b':2}
>>> l.extend(d)
['a', 'b']

>>> l2 = list()
>>> l2.append(d)
[{'a':1, 'b':2}]
在Python中,当您在字典上迭代时,它的键是一个序列,因此当使用
extends()
时,只有字典键被添加到列表中-因为Python要求的迭代器与我们在
for
循环中迭代字典时得到的迭代器相同

>>> for k in d:
        print k
a
b
>>> for k in d:
        print k
a
b