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]}
CodePudding user response:
this could be your dict-comprehension:
{k: [i if i <= 5 else i 2 for item in v] for k, v in dict_.items()}
note that you need a list-comprehension for the values as well.
noting that False
is basically 0
and True
is 1
you could simplify (but maybe making it more obscure?) the list-comprehension:
{k: [i 2 * (i > 5) for i in v] for k, v in dict_.items()}
CodePudding user response:
You can do this, but as you are working with both dicts and lists, you will want to use a list comprehension also.
my_dict ={'a':[5, 8, 7],
'b':[4, 7, 2],
'c':[2, 2, 4]}
d = {key: [x if x <= 5 else x 2 for x in value] for key, value in my_dict.items()}
This should solve the above problem and return:
{'a': [5, 10, 9], 'b': [4, 9, 2], 'c': [2, 2, 4]}
CodePudding user response:
for k, v in dict_.items():
dict_new[k] = [e 2 if e > 5 else e for e in v ]