Home > Software engineering >  Python modifying List inside a dict
Python modifying List inside a dict

Time:06-20

How to modify a dict of lists? for example: if I have a dict:

my_dict = {'numbers':[1,2,3],
'numbers2':[4,5,6]
'numbers3':[7,8,9]}

How do I, for example, do I multiply all numbers by 3? output:

my_dict = {'numbers':[3,6,9],
'numbers2':[12,15,18]
'numbers3':[21,24,27]}

CodePudding user response:

You just do it entry by entry.

for k in my_dict:
    my_dict[k] = [i*3 for i in my_dict[k]]

Note that I am creating a new list, rather than modifying the existing one in place.

CodePudding user response:

Tim's method is the easiest to understand if you're using raw Python lists. If you're using Numpy arrays, however, you could use a dict comprehension:

import numpy as np

my_dict = { "a": np.array([1, 2, 3]), "b": np.array([4, 5, 6]), "c": np.array([7, 8, 9]) }

my_dict = { k: v * 3 for k, v in my_dict.items() }
  • Related