How to change all the keys of a dictionary?

Question:

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?

Asked By: Yang L

||

Answers:

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'}
Answered By: I'mahdi

You could also make use of dict.pop():

original = {'lastname':'John', 'fistname':'Doe', 'id':'xxxxx'}

for k in original.keys():
    original[f"contact_{k}"] = original.pop(k)

print(original)

Output:

{'contact_lastname': 'John', 'contact_fistname': 'Doe', 'contact_id': 'xxxxx'}
Answered By: B Remmelzwaal
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.