3
Contributors
4
Replies
5
Views
6 Years
Discussion Span
Last Post by pyTony
Featured Replies
  • 2

    There is an interesting alternative which you easily miss as possibility: [CODE]dictionary={'a':['A'], 'b':['B'], 'c':['C']} for k,v in dictionary.items(): [dictionary[k]] = v print dictionary [/CODE] And here is version I would use in my code: [CODE]dictionary={'a':['A'], 'b':['B'], 'c':['C']} dictionary = dict((k, v) for k,[v] in dictionary.items()) print dictionary [/CODE] And finally … Read More

0
for k,v in dictionary.items():
  dictionary[k] = v[0]

http://docs.python.org/library/stdtypes.html#mapping-types-dict
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

2

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()}
print(dictionary)

Edited by pyTony: n/a

Comments
Completely useless, but interesting
0

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.

0

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.