I'm trying to extend a dict value into a list in python 2.6 When i run the extend i'm not getting all dictionary values into the list. What am i missing?
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)
Return value of cldterr:
print cldterr
{'errors': 'fail 0[file.so: undefined symbol: Device_Assign]: library file.so\r\n', 'filename': '/users/home/ili/a.pdr'}
When i attempt to extend cldterr to the list clderrors i only get:
print clderrors
['errors', 'filename']
It it because .extend() expects a sequence, you want to use append() which expects an object.
For example
>>> l = list()
>>> d = dict('a':1, 'b':2}
>>> l.extend(d)
['a', 'b']
>>> l2 = list()
>>> l2.append(d)
[{'a':1, 'b':2}]
In Python when you iterate over a dictionary you get it's keys as a sequence, hence when using extends() only the dictionary keys are added to the list - as Python is asking for the same iterator we get when iterating over the dictionary in a for loop.
>>> for k in d:
print k
a
b
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With