1

I am familiar with the struct construct from MATLAB, specifically array of structs. I am trying to do that with dictionary in Python. Say I have a initialized a dictionary:

samples = {"Name":"", "Group":"", "Timeseries":[],"GeneratedFeature":[]}

and I am provided with another dictionary called fileList whose keys are group names and each value is a tuples of file-paths. Each file path will generate one sample in samples by populating the Timeseries item. Further some processing will make GeneratedFeature. The name part will be determined by the filepath.

Since I don't know the contents of fileList a priori, in MATLAB if samples were a struct and fileList just a cell array:

fileList={{'Group A',{'filepath1','filepath2'}};{'Group B',{'filepath1', 'filepath2'}}}

I would just set a counter k=1 and run a for loop (with a different index) and do something like:

k=1;
for i=1:numel(fileList)
    samples(k).Group=fileList{i}{1};
    for j=1:numel(fileList{i}{2})
        samples(k).Name=makeNameFrom(fileList{1}{2}{j})
        .
        .
    end
    k=k+1
end

But I don't know how to do this in python. I know I can keep the two for loop approach with

for (group, samples) in fileList:
   for sample in samples:

But how to tell python that samples is allowed to be an array/list? Is there a more pythonic approach than doing for loop?

1
  • OMG!! append! Commented May 15, 2018 at 21:22

1 Answer 1

1

You could store your dictionary itself in a list and simply append new dictionaries in every iteration of the loop:

samplelist = []
samplelist.append(samples.copy()) % dictionary copy needed when duplicating

Accessing the elements in the list would then work as follows (For example the 'Name' field of the i-th sample):

samples_i_name = samplelist[i]["Name"]

A list of all names would be accessible by a simple list comprehension:

namelist = [samplelist[i]["Name"] for i in range(len(samplelist))]
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks...I am able to access it like you said samplelist[i]["Name"] but what if I wanted all names at once? Python says: TypeError: list indices must be integers or slices, not str when I use [:] notation.
Use a list comprehension (essentially a for loop in one line: namelist = [samplelist[i]["Name"] for i in range(len(samplelist))]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.