This answer combines all the suggestions in the comments. The procedure loops thru the initial list of dictionaries and does the following:
- Creates a new list is using list compression, saving each dictionary value as float, or None for non-floats.
- Counts # of float values in the new list and appends if there is at least 1 float.
- Creates an array from the new list using np.array().
I added missing quotes to starting code in original post.
Also, in the future posts you should at least make an effort to code something, then ask for help where you get stuck.
test_d = [{'a':'DOB', 'b':'weight', 'c':'height'},
{'a':12.2, 'b':12.5, 'c':11.5},
{'a':'DOB', 'b':33.5, 'c':33.2}]
arr_list = []
for d in test_d:
d_list = [x if isinstance(x, float) else None for x in d.values()]
check = sum(isinstance(x, float) for x in d_list)
if check > 0:
arr_list.append(d_list)
print (arr_list)
arr = np.array(arr_list)
print(arr)
For reference, here is the list compression converted to a standard loop with if/else logic:
for d in test_d:
# List compression converted to a loop with if/else below:
d_list = []
for x in d.values():
if isinstance(x, float):
d_list.append(x)
else:
d_list.append(None)
valuesmethod for dictionaries and see how far you get with that. Are you familiar with list comprehensions? These might be useful... Also, is your dictionary statement above valid? Have you even tried it?np.array(alist, dtype=float)is the normal way to make an array. Just iterate through the dictionary, collecting values in a list. That's straight forward Python coding. What's the problem?numpyquestion, stackoverflow.com/questions/66739758/…a,b,c, andheightall variables, or does your example miss a number of quotes?