To sum certain values in a dictionary

Asked 2 years ago, Updated 2 years ago, 78 views

{'A': [8, 4, 'Team1'], 'B': [7, 6, 'Team2'], 'C': [4, 7, 'Team1'], 'D': [5, 5, 'Team2'], 'E': [2, 9, 'Team1'], 'F': [9, 3, 'Team2'], 'G': [7, 8, 'Team1'], 'H': [6, 4, 'Team2']}

In this dictionary, I want to get the sum of the first numbers in the value list and the sum of the second numbers separately, so how do I code?

Team2: The sum of the first numbers = 27 The sum of the second numbers = 18                                                                                   
 B: first = 7, second = 6

 D: first = 5, second = 5

 F: first = 9, second = 3

  H: first = 6, second = 4

Team1: Sum of the first numbers = 21 Sum of the second numbers = 28

  A: first = 8, second = 4

 C: first = 4, second = 7

 E: first = 2, second = 9

 G: first = 7, second = 8

It should be printed like this.

dictionary

2022-09-20 19:34

2 Answers

>>> data = {'A': [8, 4, 'Team1'], 'B': [7, 6, 'Team2'], 'C': [4, 7, 'Team1'], 'D': [5, 5, 'Team2'], 'E': [2, 9, 'Team1'], 'F': [9, 3, 'Team2'], 'G': [7, 8, 'Team1'], 'H': [6, 4, 'Team2']}
>>> for k, v in data.items():
    print(k, v)


A [8, 4, 'Team1']
B [7, 6, 'Team2']
C [4, 7, 'Team1']
D [5, 5, 'Team2']
E [2, 9, 'Team1']
F [9, 3, 'Team2']
G [7, 8, 'Team1']
H [6, 4, 'Team2']
>>> sum1 = 0
>>> sum2 = 0
>>> for k, v in data.items():
    sum1 += v[0]
    sum2 += v[1]


>>> sum1, sum2
(48, 46)
>>> sum1t1, sum1t2, sum2t1, sum2t2 = 0, 0, 0, 0
>>> for k, v in data.items():
    if v[2] == 'Team1':
        sum1t1 += v[0]
        sum2t1 += v[1]

>>> sum1t1, sum1t2, sum2t1, sum2t2
(21, 0, 28, 0)


2022-09-20 19:34

val M = Map("A" -> Seq(8, 4, "Team1"), "B" -> Seq(7, 6, "Team2"), "C" -> Seq(4, 7, "Team1"), "D" -> Seq(5, 5, "Team2"), "E" -> Seq(2, 9, "Team1"), "F" -> Seq(9, 3, "Team2"), "G" -> Seq(7, 8, "Team1"), "H" -> Seq(6, 4, "Team2"))

M.values
 .groupBy(_(2))
 .foreach(pair => println(s"${pair._1} ${pair._2.collect { case l => l(0).asInstanceOf[Int] }.sum} ${pair._2.collect { case l => l(1).asInstanceOf[Int] }.sum}"))

=> Team2 27 18
   Team1 21 28


2022-09-20 19:34

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.