-1
\$\begingroup\$

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)
\$\endgroup\$

closed as off-topic by yuri, Stephen Rauch, Graipher, Mast, Sᴀᴍ Onᴇᴌᴀ Aug 19 '18 at 3:40

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "Lacks concrete context: Code Review requires concrete code from a project, with sufficient context for reviewers to understand how that code is used. Pseudocode, stub code, hypothetical code, obfuscated code, and generic best practices are outside the scope of this site." – yuri, Stephen Rauch, Graipher, Mast, Sᴀᴍ Onᴇᴌᴀ
If this question can be reworded to fit the rules in the help center, please edit the question.

  • \$\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
3
\$\begingroup\$

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'])
\$\endgroup\$
  • \$\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.