简体   繁体   中英

Python string to array : TypeError: iteration over a 0-d array

I have a string from a field in a query set which looks like this:

[{'thirdParty': 'Funds Transfer'}, {'category': 'External Transfers'}, {'creditDebit': 'credit'}]

I want to be able to loop through the elements in orther to be able to get

{'thirdParty': 'Funds Transfer'}
{'category': 'External Transfers'}
{'creditDebit': 'credit'} 

And also to be able to loop through the keys of that object

I am trying the following but I keep getting an error: TypeError: iteration over a 0-d array

import numpy as np
tags = "[{'thirdParty': 'Funds Transfer'}, {'category': 'External Transfers'}, {'creditDebit': 'credit'}]"
# print(type(tags))
# <class 'str'>
arr = list(np.array(tags))
# print(type(tags))
# <class 'numpy.ndarray'>
# print(tags)
# [{'thirdParty': 'Funds Transfer'}, {'category': 'External Transfers'}, {'creditDebit': 'credit'}]
for d in arr:
    print(d)

try this because you added Double quotes in tags

import numpy as np
tags = [{'thirdParty': 'Funds Transfer'}, {'category': 'External Transfers'}, {'creditDebit': 'credit'}]
arr = list(np.array(tags))
# print(type(tags))
# <class 'numpy.ndarray'>
# print(tags)
# [{'thirdParty': 'Funds Transfer'}, {'category': 'External Transfers'}, {'creditDebit': 'credit'}]
for d in arr:
    print(d)

output

{'thirdParty': 'Funds Transfer'}
{'category': 'External Transfers'}
{'creditDebit': 'credit'}
import ast

tags = "[{'thirdParty': 'Funds Transfer'}, {'category': 'External Transfers'}, {'creditDebit': 'credit'}]"
tags_list = ast.literal_eval(tags)

print(tags_list)

Output:

[
    {"thirdParty": "Funds Transfer"},
    {"category": "External Transfers"},
    {"creditDebit": "credit"},
]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM