1

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)

2 Answers 2

3

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'}
Sign up to request clarification or add additional context in comments.

5 Comments

it works perfect when i try from a python online, but not when i try from django, i am wonder why, the error stills: iteration over a 0-d array
tags is already a list...why make a numpy array and then immediately make a list just to get back where you started?
@MarkMeyer that is not correct when I print(type(key.tags)) i get <class 'str'>, it doesnt said <class 'list'>
if you give string to numpy array it will show 0-d array you have to give list where you can check lis[0][0]='thirdParty': 'Funds Transfer'.
@NAGARAJS exactly that is precisely my question
1
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"},
]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.