0
votes

I have a dictionary with five keys and three values corresponding to each key:

mySubList1 = [[1, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6], [2, 8, 4, 6, 7, 8, 9, 10, 11, 12, 12, 13]]
mySubList2 = [[0, -1, 3, 4, 4, 6, -2, 3, 1, 0, -20, -2], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 15]]
mySubList3 = [[2, 2, 3, 4, 5, 6, 6, 5, 4, 3, 2, 1], [-1, -3, 44, 22, 4, 7, 7, 8, 9, 10, 11, 20]]

my_dictionary = {
            "Dimensions: ": [],
            "Shape: ": [],
            "Mean: ": [],
            "Median: ": [],
            "Standard Deviation: ": [],
        }

for i in mySubList1, mySubList2, mySubList3:
    print(i)
    my_dictionary['Dimensions: '].append(np.ndim(i))
    my_dictionary['Shape: '].append(np.shape(i))
    my_dictionary['Mean: '].append(np.mean(i))
    my_dictionary['Median: '].append(np.median(i))
    my_dictionary['Standard Deviation: '].append(np.std(i))

What I am trying to do is iterate over each of the key-value pairs, in the format: Set 1 Key1: Value1 Key2: Value1 Key3: Value1 Key4: Value1 Key5: Value1

Set 2 Key1: Value2 Key2: Value2 Key3: Value2 Key4: Value2 Key5: Value2

And so on.

What I have so far is:

for key, value in my_dictionary.items():
    print(key, value)

Which gives me an undesired output in the format:

Key1: Value1, Value2, Value3

Any pointers?

1
"with five keys and three values corresponding to each key" No, keys are associated with exactly one value alwaysjuanpa.arrivillaga
Since you want your data to come out as a list of attributes of grouped by sublist, have you thought about switching your data structure to being a list of dictionaries instead of a dictionary of lists?Malcolm
@Malcolm I mean, it really depends on the resulting use-case. Generally, I would say, a list of dictionaries is rarely the right approach. Often, you will get that as a result of deserializng some JSON or Yaml. But if you are going to do that, you should really be defining your own record type and use that instead of a dict.juanpa.arrivillaga
When you don't need methods on your data there is no real advantage to creating a new class for your record. A simple dict does exactly what you want. When you use a csv.DictReader you get exactly this type of structure. I would hardly say that csv.DictReader is not "right" for doing it this way. Of course, it does depend upon what you want to do with the data, but it sounds like this is what @LG1 is asking for.Malcolm

1 Answers

1
votes

If you want to organize your data by sublist, swap your data structure from being a dictionary of lists to be a list of dictionaries

my_list = []
for i in mySubList1, mySubList2, mySubList3:
    my_list.append({
        'Dimension': np.ndim(i),
        'Shape': np.shape(i),
        'Mean': np.mean(i),
        'Median': np.median(i),
        'Standard Deviation': np.std(i)
    })

now just print(my_list) almost gives you what you want.