0

Given a dictionary, d, of type {key: (v1,v2)}, I'd like to perform a division on v1,v2 for all keys to produce a score, v3 so my dict is of type {key: (v1,v2,v3)}.

I understand I can do:

for key,v1,v2 in d.items():
    score = v1/v2 

But can't work out how to then store this in the dictionary.

R__raki__
  • 847
  • 4
  • 15
  • 30
user1893110
  • 241
  • 1
  • 3
  • 12

2 Answers2

6

This is an easy case for a dict comprehension:

d2 = {key: (v1,v2,v1/v2) for key,(v1,v2) in d.items()}
John Zwinck
  • 239,568
  • 38
  • 324
  • 436
1
# Example dict
d = {
    "a": (1, 2),
    "b": (3, 4)
}

# Dict comprehension
scores = { k : (v1, v2, v1 / v2) for k, (v1, v2) in d.items()}
honza_p
  • 2,073
  • 1
  • 23
  • 37