# Building a dynamic dictionary mapper inside function

I have one function attrmapper. The purpose for this function is to build a dictionary, information, as attribution for the object. Is there a better way for me to rewrite the obj.information.update( part? The part to update information attribution will be more clear? Because if we replace mapping to a long string, the function will be really hard to read.

mapping = {
'firstname': 'this is fisrt name: {} should be string',
'lastname': 'this is last name: {} should be string',
'phone_number': 'this is phone number {} should be 0 to 9',
'gender': 'this is gender {}: should be male or female',
'position': 'this is position {} should be engineer, manager and level',
'aAbreu': 'Albert Abreu',
'lCessa': 'Luis Cessa',
'aJudge': 'Aaron Judge',
'jEllsbury': 'Jacoby Ellsbury',
}
def attrmapper(obj: object) -> object:
information = {}
for name in ['aAbreu', 'cGreen', 'lCessa', 'aJudge', 'jEllsbury']:
obj.information.update(
{'{}_firstname'.format(name): mapping.get('firstname').format(mapping.get(name)),
'{}_lastname'.format(name): mapping.get('lastname').format(mapping.get(name)),
'{}_phone_number'.format(name): mapping.get('phone_number').format(mapping.get(name)),
'{}_company'.format(name): mapping.get('company').format(mapping.get(name)),
'{}_position'.format(name): mapping.get('firstname').format(mapping.get(name))})
return obj


We can do a dictionary comprehension and avoid code repetition:

NAMES = ['aAbreu', 'cGreen', 'lCessa', 'aJudge', 'jEllsbury']
ATTRIBUTES = ['firstname', 'lastname', 'address', 'phone_number', 'company', 'position']
for name in NAMES:
full_name = mapping.get(name)
obj.information.update({
f'{name}_{attr}': mapping.get(attr).format(full_name)
for attr in ATTRIBUTES
})


Note the use of an f-string for the key definition.

And, aside from that, I think you can remove the information variable as it is unused.

And, both my and your versions of the code don't handle missing keys situation - what if there is no such key in mapping?

• thank you. yes, update the code for copy and paste error and if missing key, my function cannt even run at all i assume Dec 3 '17 at 15:33
• @SimonForsberg I was operating under the assumption that there was a copy-paste error in the question and as we figured out, there was one. In other words, I think the answer now "matches" the question fine. Thanks! Dec 3 '17 at 17:04
• If only somebody had told me about the power of f-string years ago. I used to pull some stunts to get the same thing done. Bloody genius, good answer.
– Mast
Dec 3 '17 at 20:25
• well, f-strings are pretty new, so it wouldn't have been great advice more than a year or two ago. Dec 18 '17 at 4:27
• @OscarSmith yeah, but their awesomeness level is close to maximum :) Dec 18 '17 at 4:28