7 Years
Discussion Span
Last Post by pyTony
for k,v in dictionary.items():
  dictionary[k] = v[0]

You can use dictionary.iteritems() if you prefer, but beware "Using iteritems() while adding or deleting entries in the dictionary may raise a RuntimeError or fail to iterate over all entries.". Fortunately, we aren't adding or removing here, just changing the value associated with the key.

Edited by griswolf: n/a


There is an interesting alternative which you easily miss as possibility:

dictionary={'a':['A'], 'b':['B'], 'c':['C']}
for k,v in dictionary.items():
  [dictionary[k]] = v

print dictionary

And here is version I would use in my code:

dictionary={'a':['A'], 'b':['B'], 'c':['C']}
dictionary = dict((k, v)
                  for k,[v] in dictionary.items())
print dictionary

And finally Python 3 (and 2.7) dict comprehension:

from __future__ import print_function
dictionary={'a':['A'], 'b':['B'], 'c':['C']}
dictionary = { k : v
              for k,[v] in dictionary.items()}

Edited by pyTony: n/a

Votes + Comments
Completely useless, but interesting

Hi tonyjv.
I'm still trying to wrap my mind around your inversion of the [], but aside from that, the code I would write is the same as the code you would use. Thanks for that bit of syntax... now I'll have to go do some reading.


And that is not all, try it with function parameters. It is still bit too strict for format of parameters. Have to have correct place to use, say passing in 2d coordinates as tuple and use x,y without indexing. Easy to go against spirit of duck typing. Performance I have not tested.

Edited by pyTony: n/a

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.