How do I change all keys of a dictionary
code:
d1 = {'mango':10,
'bananna':20,
'grapes':30}
d1_new_keys = ['yellow mango','green banana','red grapes']
d1.keys() = d1_new_keys
present answer:
SyntaxError: can't assign to function call
expected answer:
d1 = {'yellow mango': 10, 'green bananna': 20, 'red grapes': 30}
>Solution :
What you’re doing is trying to set the function d1.keys() to a list thus the error. The best way to do this would be with dictionary comprehension:
d1 = {k: v for (k, v) in zip(d1_new_keys, d1.values()}
This would essentially create a new dictionary and set it equal to d1 where the keys come from the d1_new_keys list and the values come from the original d1