Malformed String error - Python - converting strin

2019-06-03 17:51发布

问题:

When I do ast.literal_eval(), I get ValueError: malformed string for the line below z = ast.literal_eval(a). Why is this not working?

(Pls. note - "something" in the line below has 4 or more namedtuples)

for thing in something:

    a = thing._asdict()

    z = ast.literal_eval(a)
    print z

If I do a simple print a, I get

OrderedDict([('a', 0.0), ('b', 0.0), ('c', 0.0), ('d', 100.0)])

Without ast.literal_eval(a), when I try to use "a" as a dictionary, it raises AttributeError: 'str' object has no attribute 'items'. Here's the expanded code --

for thing in something:

    a = thing._asdict()
    print a


    z = ast.literal_eval(a)
    print a



    d = {}
    for in_d in z:

        for k, v in in_d.iteritems():
            d.setdefault(k, []).append(v)  
            print d

    merged = {}
    for d in z:
        d=d[1:-1]

        for k, v in d.items():
            if k not in merged: merged [k] = []
            merged [k].append (v)
            print merged

Edit: When I try json.loads(thing), I get TypeError: expected string or buffer. So I think thing is not a string. Then I don't know why it is complaining that it is a str object when I use it.