Home > Back-end >  elegant way of multiplying all integers in lists in a dict
elegant way of multiplying all integers in lists in a dict

Time:09-14

I have a dictionary whith strings that map to lists of integers. I want to multiply each item in each list by a certain integer. What's the most elegant way to do this?

This does not work:

mydict = {'a':[1,2,3],'b':[3,4,5],'c':[8,7,6]}
for val in mydict.values():
  for i in val:
    i *= 3

This doesn't work either:

for val in mydict.values():
  val = [val[s]*2/3 for s in range(len(val))]

This works but seems overly complicated:

for key in mydict:
  mydict[key] = [mydict[key][value]*3 for value in mydict[key]]

Is there a nice way to do this?

CodePudding user response:

Try this in one line:

mydict = {"a": [1, 2, 3], "b": [3, 4, 5], "c": [8, 7, 6]}
mydict = {k: [i * 3 for i in v] for k, v in mydict.items()}

the output will be:

Out[6]: {'a': [3, 6, 9], 'b': [9, 12, 15], 'c': [24, 21, 18]}

also you can use map():

mydict = {k: list(map(lambda x: x * 3, v)) for k, v in mydict.items()}

CodePudding user response:

If you want to update in place:

mydict = {'a':[1,2,3],'b':[3,4,5],'c':[8,7,6]}
for l in mydict.values():
    l[:] = [x*3 for x in l]

updated mydict:

{'a': [3, 6, 9], 'b': [9, 12, 15], 'c': [24, 21, 18]}

CodePudding user response:

Use index to directly update the array. No need to create a new array or dictionary since arrays are mutable. This way it will be faster.

mydict = {'a': [1, 2, 3], 'b': [3, 4, 5], 'c': [8, 7, 6]}
for val in mydict.values():
    for i in range(len(val)):
        val[i] *= 3

print(mydict)

UPDATE: Execution time of the various solutions:

import timeit

timeit.timeit()

code1 = '''mydict = {'a': [1, 2, 3], 'b': [3, 4, 5], 'c': [8, 7, 6]}
for val in mydict.values():
    for i in range(len(val)):
        val[i] *= 3'''
print(timeit.timeit(stmt=code1, number=1000000))

code2 = '''mydict = {"a": [1, 2, 3], "b": [3, 4, 5], "c": [8, 7, 6]}
mydict = {k: [i * 3 for i in v] for k, v in mydict.items()}'''
print(timeit.timeit(stmt=code2, number=1000000))

code3 = '''mydict = {'a': [1, 2, 3], 'b': [3, 4, 5], 'c': [8, 7, 6]}
{k: list(map(lambda x: x * 3, v)) for k, v in mydict.items()}'''
print(timeit.timeit(stmt=code3, number=1000000))


code4 = '''mydict = {'a': [1, 2, 3], 'b': [3, 4, 5], 'c': [8, 7, 6]}
for l in mydict.values():
    l[:] = [x*3 for x in l]'''
print(timeit.timeit(stmt=code4, number=1000000))

Result:

1.4062689999991562
1.4332131000010122
1.9182285999995656
1.394005999998626

Ran this several times and the results vary each time, but mostly I see code4 is the faster solution followed by code1.

  • Related