Could anyone help me with what's wrong with the code below:
k = {'boy':[2,3,6,8],
'girl':[3,5,7,9]
}
n = 2
m = {}
for (key, value) in k.items():
m[key] = [
n * value for value in k.values()
]
print(m['boy'])
[[2, 3, 6, 8, 2, 3, 6, 8], [3, 5, 7, 9, 3, 5, 7, 9]]
I need a result that would multiply n by each value of the list elements within the dictionary. SSo the result is supposed to come out as:
m = {'boy':[4,6,12,16],
'girl':[6,10,14,18]}
CodePudding user response:
In python you can't multiply lists with the *
operator as this is reserved for repeating lists:
[0] * 5
result: [0, 0, 0, 0, 0]
You could do this in two ways:
- You use
numpy
arrays which do support this behaviour. - You explicitly multiply each element. For example like:
k = {'boy':[2,3,6,8],
'girl':[3,5,7,9]
}
n = 2
m = {}
for (key, value) in k.items():
m[key] = [
n * one_value for one_value in value
]
I also just noticed you were overwriting the variable value
. Be careful with this as this can lead to hard to find issues. Preferably always use an unused name for a variable where possible, unless you really mean to reuse one. Also you were selecting from k.values()
which are all the lists in that dictionary, not just the one you want to be manipulating.
CodePudding user response:
You are not assigning the key and values properly :
k = {'boy':[2,3,6,8],
'girl':[3,5,7,9]
}
n = 2
m = {}
for (key, value) in k.items():
m[key] = key
m[key] = [
n * val for val in value
]
print(m['boy'])
print(m['girl'])
output :
[4, 6, 12, 16]
[6, 10, 14, 18]
CodePudding user response:
The problem is that , you are iterating on the main dictionary values with k.values()
, instead you can just use the value
in the item.
like
m[key] = [
n * val for val in value
]
And a bonus one-liner for you
m = {key:list(map(lambda x: x*n, value)) for key,value in k.items()}
CodePudding user response:
k = {'boy': [2,3,6,8],
'girl': [3,5,7,9]}
n = 2
m = {key: [v * n for v in value]
for key, value in k.items()}
If you are not familiar with comprehensions, this gives the same result
m = {}
for key, value in k.items():
l = []
for v in value:
l.append(v * n)
m[key] = l
The version with comprehensions is faster and in my opinion more readable.