-4

I would like to multiply the keys of this dictionary by 2

d = {2: (1,2), 8: (2,4), 30: (10,3)}

for i in d.keys():
    print(i*2)

4
16
60

But d is still {2: (1,2), 8: (2,4), 30: (10,3)}

How can I get d to become {4: (1,2), 16: (2,4), 60: (10,3)} ?

vahdet
  • 6,357
  • 9
  • 51
  • 106
wussyx
  • 85
  • 1
  • 5
  • This does not make any sense. Do you want the key to multiply with each value or just the first one? – DirtyBit Feb 18 '19 at 07:58
  • see if the answer posted below helped? if it did, you may accept it by clicking on the tick sign beside it. cheers! – DirtyBit Feb 18 '19 at 15:18

5 Answers5

0

Can you try the following:

d = {2: (1,2), 8: (2,4), 30: (10,3)}
d = {k**2: v for k, v in d.items()}
Jeril
  • 7,858
  • 3
  • 52
  • 69
0

dictionary comprehension:

double = {k*2:v for (k,v) in d.items()}
bollence
  • 109
  • 5
0

I believe you want is:

Multiply each key with 2. Not the square of it.

d = {2: (1,2), 8: (2,4), 30: (10,3)}
d = {k*2: v for (k, v) in d.items()}
print(d)

OUTPUT:

{4: (1, 2), 16: (2, 4), 60: (10, 3)}
DirtyBit
  • 16,613
  • 4
  • 34
  • 55
0
new_d = {}
for k,v in d.items():
    new_d[k*2] = v
d = new_d
Rashid Mahmood
  • 313
  • 4
  • 10
0

Try this:

d = dict((key*2, value) for (key, value) in d.items())
Mehrdad Pedramfar
  • 10,941
  • 4
  • 38
  • 59