Home > Back-end >  Print the last element in a dictionary in a set
Print the last element in a dictionary in a set

Time:08-17

I need to select the last element from the following output.

print(result)
[('ABC', 880, {0: 'A', 1: 'P', 2: 'O', 3: 'T', 4: 'S'}),
('CDE', 120, {0: 'S', 1: 'E', 2: 'N'}),
('EFG', 240, {0: 'G', 1: 'R'})]

Desired output:

[S,N,R]

CodePudding user response:

Assuming a list l of tuples as input:

out = [list(t[-1].values())[-1] for t in l]

output: ['S', 'N', 'R']

To print:

print(*out, sep='\n')

output:

S
N
R

CodePudding user response:

Maybe something like this?

alist = [
    ('ABC', 880, {0: 'A', 1: 'P', 2: 'O', 3: 'T', 4: 'S'}),
    ('CDE', 120, {0: 'S', 1: 'E', 2: 'N'}),
    ('EFG', 240, {0: 'G', 1: 'R'})
]

print([adict[max(adict)] for _, _, adict in alist])

Output:

['S', 'N', 'R']

CodePudding user response:

Assuming you have a list of tuples and each tuple has three elements of which the last is a dictionary then you could do this:

list_ = [
    ('ABC', 880, {0: 'A', 1: 'P', 2: 'O', 3: 'T', 4: 'S'}),
    ('CDE', 120, {0: 'S', 1: 'E', 2: 'N'}),
    ('EFG', 240, {0: 'G', 1: 'R'})
]

for _, _, d in list_:
    print(list(d.values())[-1])

Output:

S
N
R
  • Related