I have a dictionary (dict_) with lists of integers as values. I want to make an operation on these list and save the result as a new dictionary.
Below I do an operation on these list, adding 2 if the elements are larger than 5. I use a nested for loop to achieve this. How would I achieve the same using dictionary comprehension?
dict_={'a':[5, 8, 7],
'b':[4, 7, 2],
'c':[2, 2, 4]}
print(dict_)
#Output: {'a': [5, 8, 7], 'b': [4, 7, 2], 'c': [2, 2, 4]}
dict_new = {}
for k, v in dict_.items():
list_temp=[]
for e in v:
if e > 5:
ne=e + 2
list_temp.append(ne)
else:
list_temp.append(e)
dict_new[k] = list_temp
print(dict_new)
# Output: {'a': [5, 8, 7], 'b': [4, 7, 2], 'c': [2, 2, 4]}