2

I have this dictionary:

data = {'x': [1, 2, 3]}

I would like to multiply the list of the key 'x' by a scalar for example:

data['x']*2

but I obtain:

[1, 2, 3, 1, 2, 3]

insted of:

[2, 4, 6]

How can I do that? Thanks

gaetano
  • 785
  • 12
  • 28

2 Answers2

1

Don't multiply the list by two, multiply each element by two and reassign to the key 'x'.

>>> data = {'x': [1, 2, 3]}
>>> data['x'] = [2*x for x in data['x']]
>>> data
{'x': [2, 4, 6]}

(The reassignment is optional depending on what you try to do)

timgeb
  • 73,231
  • 20
  • 109
  • 138
1

You need to iterate over its elements:

  map(lambda x: x * 2, data['x'])
Incerteza
  • 27,981
  • 42
  • 142
  • 242