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?
Answers:
If you want to correct your code, you can iterate over key
s 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'}
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'}
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?
If you want to correct your code, you can iterate over key
s 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'}
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'}