I am a beginner in Python and have several exercises to resolve.
One of these is:
"Define a dictionary w/ keys "abc", "xyz" and values [1, 2, 3] and [9, 10, 11]; iterate over all values (lists) and raise to the power of 4 each element of each list and print to screen"
...and I am bit lost. I could define a function that raises the power of each element in a list, but I do not know how to do it in a dictionary :(
This is where I am stuck:
dex = {"abc":[1,2,3],"xyz":[9,10,11]}
for x in dex.values():
print(x)
CodePudding user response:
Since it's nested you could use a loop in a loop to get each item of each list, like this:
dex = {"abc":[1,2,3],"xyz":[9,10,11]}
for x in dex.values():
for el in x:
print(el**4)
or using dict and list comprehension:
dex = {"abc":[1,2,3],"xyz":[9,10,11]}
dex = {k: [el**4 for el in v] for k, v in dex.items()}
print(dex)
CodePudding user response:
This way should work, if you can use dict comprehensions. It uses map
, which applies a function to each elem in a list.
my_dict = {"abc": [1, 2, 3], "xyz": [9, 10, 11]}
new_dict = {key: list(map(lambda x: x ** 4, val)) for key, val in my_dict.items()}
Here, we map a function that raises each item in the list to a power.
CodePudding user response:
Depending on how you want to present the output, this might work for you:
dex = {"abc": [1,2,3], "xyz": [9,10,11]}
print([[e**4 for e in lst] for lst in dex.values()])
Output:
[[1, 16, 81], [6561, 10000, 14641]]
CodePudding user response:
This should work :
dex = {"abc":[1,2,3],"xyz":[9,10,11]}
def print_exp (dic) :
for i,j in dic.items() :
if isinstance(j,list):
for n in j :
print(n**4)
print_exp(dex)
This one is with a function definition.
Without function definition you can achieve this by :
dex = {"abc":[1,2,3],"xyz":[9,10,11]}
for i,j in dex.items() :
if isinstance(j,list):
for n in j :
print(n**4)