user3176335
user3176335

Reputation: 192

Get only last tuple from dictionary

I have a nested dictionary "inputlist". Each list has 3 tuple. I want to put only first value of third tuple in "mean" variable.

Here is my code:

inputlist={
      1: {0: [(5.6, 3.6), (20.0, 0.0), (1.0, 0.0)]},
      2: {0: [(2.5, 0.5), (21.5, 0.5), (2.0, 2.1)],
          1: [(4.0, 0.0), (22.0, 0.0), (3.0, 3.1)]},
      3: {0: [(5.0, 0.0), (23.0, 0.0), (4.0, 2.3)],
          1: [(7.0, 0.0), (24.0, 0.0), (5.0, 3.3)]},
     }


for k1, v1 in inputlist.items():
    for (classValue, classModels) in v1.items():
        
         for i in range(len(classModels)):
            (mean, stdev) = classModels[i]
            print(mean)
          

Output should be like this:

Mean: 
1.0
2.0
3.0
4.0
5.0

Upvotes: 0

Views: 155

Answers (3)

MichaelRSF
MichaelRSF

Reputation: 896

for key in inputlist:
    
    for subkey in inputlist[key]:
        
        print(inputlist[key][subkey][2][0])
       
            

Upvotes: 1

PCM
PCM

Reputation: 3011

You can try this -

for keys in inputlist:
    for a in inputlist[keys].values():
        print(a[2][0]) # 3rd  element of list # 1st element in tuple   

Result:

1.0
2.0
3.0
4.0
5.0

Upvotes: 0

0x5CD59377
0x5CD59377

Reputation: 1

This is a pretty straightforward nested dict/list/tuple problem. Just grab the third tuple’s first element in each of the nested dict values.

inputlist = {
    1: {
        0: [(5.6, 3.6), (20.0, 0.0), (1.0, 0.0)]
    },
    2: {
        0: [(2.5, 0.5), (21.5, 0.5), (2.0, 2.1)],
        1: [(4.0, 0.0), (22.0, 0.0), (3.0, 3.1)]
    },
    3: {
        0: [(5.0, 0.0), (23.0, 0.0), (4.0, 2.3)],
        1: [(7.0, 0.0), (24.0, 0.0), (5.0, 3.3)]
    },
}

for k, v in inputlist.items():
    for (classValue, classModels) in v.items():
        print(classModels[2][0])

Output:

1.0
2.0
3.0
4.0
5.0

Upvotes: 0

Related Questions