loop keys and values, process key values, and save them with another dictionary in Python

advertisements

I want to multiply the all the values stored in a dictionary. Can you suggest me the good way of doing that.

dict = {'x': [645, 469,456,790,850],
        'y': [599, 548],
        'z': [653,  672,150,590],
        'w': [653, 672,150,590]}
list = []
for i, j in dict.iteritems():
    #loop over all key's and get the values out and multiply with 1000
    value_ofkey = float(j[0])
    list.append = value_ofkey *1000
    value_ofkey = float(j[1])
list.append = value_ofkey *1000


Firstly do not name your variable as dict as it is a builtin.

Now to solve your problem you can try a list-comprehesion within a dict-comprehension.

>>> dic = {'x': [645, 469,456,790,850],
...         'y': [599, 548],
...         'z': [653,  672,150,590],
...         'w': [653, 672,150,590]}
>>> newdic = {key:[i*1000 for i in val] for key,val in dic.items()}
>>> newdic
{'y': [599000, 548000], 'x': [645000, 469000, 456000, 790000, 850000], 'z': [653000, 672000, 150000, 590000], 'w': [653000, 672000, 150000, 590000]}

POST COMMENT EDIT

You can restrict the required keys using if condition.

newdic = {key:[i*1000 if key != 'x' else i for i in val] for key,val in dic.items()}

For a number of such keys you can try

newdic = {key:[i*1000 if key not in ('x','y') else i for i in val] for key,val in dic.items()}

Working

>>> newdic = {key:[i*1000 if key != 'x' else i for i in val] for key,val in dic.items()}
>>> newdic
{'y': [599000, 548000], 'x': [645, 469, 456, 790, 850], 'z': [653000, 672000, 150000, 590000], 'w': [653000, 672000, 150000, 590000]}
>>> newdic = {key:[i*1000 if key not in ('x','y') else i for i in val] for key,val in dic.items()}
>>> newdic
{'y': [599, 548], 'x': [645, 469, 456, 790, 850], 'z': [653000, 672000, 150000, 590000], 'w': [653000, 672000, 150000, 590000]}