I have a piece of code which follows this form. Is this correct or is there a better way?

for i, c in enumerate(contacts):
    fullname = c['Person__FirstName'] + ' ' + c['Person__LastName']
    contacts[i]['fullname'] = create_a_tag('/contact/'+str(c['PersonSk']), fullname)
  • \$\begingroup\$ I don't see why this should be closed. Short entries of code, that do follow Code Review rules, are on-topic. \$\endgroup\$ – Alex L Jul 31 '14 at 20:46
  • 1
    \$\begingroup\$ @AlexL because of example code. You don't have foofield in a real application. \$\endgroup\$ – Pimgd Jul 31 '14 at 21:27

I have the feeling that there's some context information missing. Anyway, note that list_of_dictionaries[i] is actually the same object as r.

The same code with some variables renamed would be as follows:

for index, dictionary in enumerate(dictionaries):
    dictionary['foofield'] = foofinder(dictionary['barfield'], dictionary['bazfield'])

In the new code the index is not used at all, so the code could be simplified as follows:

for dictionary in dictionaries:
    dictionary['foofield'] = foofinder(dictionary['barfield'], dictionary['bazfield'])
| improve this answer | |
  • \$\begingroup\$ I had thought in this way that dictionary was a copy just scoped to the loop. Glad to learn that's not the case. \$\endgroup\$ – Matt Jul 31 '14 at 14:34
  • \$\begingroup\$ Ok, I see. For the future, you can test that assumption as follows: for index, dictionary in enumerate(dictionaries): print dictionary is dictionaries[i] \$\endgroup\$ – jcollado Jul 31 '14 at 14:42

Not the answer you're looking for? Browse other questions tagged or ask your own question.