I have a dictionary like this {'lastname':'John', 'fistname':'Doe', 'id':'xxxxx'}
and I would like to add a prefix to all key values. The outcome should look like
{'contact_lastname':'John', 'contact_fistname':'Doe', 'contact_id':'xxxxx'}
I tried to achieve this by a lambda function, but did not work.
original = {'lastname':'John', 'fistname':'Doe', 'id':'xxxxx'}
modified = {(lambda k: 'contact_'+k) :v for k,v in original}
But it gives me an error. Any suggestions?
>Solution :
If you want to correct your code, you can iterate over keys and create tuple(k, v) and pass it to dict.
modified = dict(('contact_'+k, original[k]) for k in original)
Or you can use dict comprehension & f-string.
original= {'lastname':'John', 'fistname':'Doe', 'id':'xxxxx'}
modified = {f'contact_{k}' : v for k,v in original.items()}
print(modified)
{'contact_lastname': 'John', 'contact_fistname': 'Doe', 'contact_id': 'xxxxx'}