I have dictionary with single element lists.

dictionary={'a':['A'], 'b':['B'], 'c':['C']}

How can i change it to

{'a':'A', 'b':'B','c':'C'}
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 6 Years Ago 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()}
print(dictionary)

Edited 6 Years Ago by pyTony: n/a

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 6 Years Ago by pyTony: n/a

This question has already been answered. Start a new discussion instead.