Jeff
Jeff

Reputation: 3

Iterate over a list of dict

There is a list of dictionary like this :

dic = {'image' : np.array, 'image_name' : 'str'}
my_list = [dic_0, dic_1, dic_2, ..., dic_n]

Then I want to get all images in this list of dictionary to create another image list, it will be :

image_list = [np.array, np.array, np.array, ...]

As far as I can think of doing it is :

image_list = []
for dic in dic_list:
    image = dic['image']
    image_list.append(image)
return image_list

Is there any better way to do this?

Upvotes: 0

Views: 86

Answers (3)

bmasri
bmasri

Reputation: 432

I would recommend using panda's json.normalize in a nice one liner. You can use a dictionary or a list of dictionary (which I believe is your case). This function returns a pandas dataframe from which you can easily select the column that contains your images as follows :

import numpy as np
import pandas as pd

# your dictionaries
dic_0 = {'image' : np.array([1,2,3]), 'image_name' : 'img_1'}
dic_1 = {'image' : np.array([6,8,10]), 'image_name' : 'img_2'}
dic_2 = {'image' : np.array([10,20,30]), 'image_name' : 'img_3'}

# your list of dictionaries
my_list = [dic_0, dic_1, dic_2]

# all of your images stored in a list
all_imgs = pd.json_normalize(my_list)['image'].tolist()
print(all_imgs)

>>> [array([1, 2, 3]), array([ 6,  8, 10]), array([10, 20, 30])]+

Upvotes: 0

Hrushi
Hrushi

Reputation: 325

Yes you try this:

def check(x):
   image_list = []
   for i in x:
       image = x[i]
       image_list.append(image)
   return image_list
req=check(dic)

Then Simply Call check function.

Upvotes: 0

NTamez8
NTamez8

Reputation: 107

Better can be a little subjective on things. This can be done using list comprehension which is a python feature that can be used to shorten loops like this

image_list = [dic['image'] for dic in dic_list]

This should work as long as all the items in the list have an image key

Upvotes: 1

Related Questions