Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python extend dict value to list

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']
like image 763
user1943219 Avatar asked Dec 10 '25 09:12

user1943219


1 Answers

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
like image 112
dannymilsom Avatar answered Dec 11 '25 23:12

dannymilsom



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!