1

Here is my OrderedDict

o=OrderedDict([('xmllist', 123), ('A', 124), ('B', 125), ('C', 126), ('D', 127)])

How can i interchange its keys and values as ,

o=OrderedDict([('A', 123), ('B', 124), ('C', 125), ('D', 126)])
Nishant Nawarkhede
  • 8,234
  • 12
  • 59
  • 81
  • possible duplicate of [Python: Best Way to Exchange Keys with Values in a Dictionary?](http://stackoverflow.com/questions/1031851/python-best-way-to-exchange-keys-with-values-in-a-dictionary) – M4rtini Feb 13 '14 at 09:23
  • It seems like the question derived from [the answer of the previous question](http://stackoverflow.com/a/21746599/2225682). You'd better build desired key, value pair from the beginning. instead of change it later. – falsetru Feb 13 '14 at 09:26
  • @falsetru Yes ! it is derived from the previous one. Can you please tell me how to build desired key and value pair ? – Nishant Nawarkhede Feb 13 '14 at 09:29
  • @Nishant, The expected result in the question does not agree with the title. It just remove `xmllist` from the dictionary. Is that what you want? – falsetru Feb 13 '14 at 09:31
  • @falsetru Yes , want to remove `xmllist` from the dictionary. – Nishant Nawarkhede Feb 13 '14 at 09:32

1 Answers1

3

Using zip and itertools.islice:

>>> from collections import OrderedDict
>>> import itertools
>>>
>>> o = OrderedDict([('xmllist', 123), ('A', 124), ('B', 125), ('C', 126), ('D', 127)])
>>> OrderedDict((key1, o[key2]) for key1, key2 in zip(itertools.islice(o, 1, None), o))
OrderedDict([('A', 123), ('B', 124), ('C', 125), ('D', 126)])

mapping: o['A'] = o['xmllist'], o['B'] = o['A'], o['C'] = o['B'], ...

falsetru
  • 357,413
  • 63
  • 732
  • 636
  • >>> o = OrderedDict([('xmllist', 123), ('A', 124), ('B', 125), ... ('C', 126), ('D', 127)]) >>> del o['xmllist'] >>> o OrderedDict([('A', 124), ('B', 125), ('C', 126), ('D', 127)]) This is what i want but want to make values interchange like , o=OrderedDict([('A', 123), ('B', 124), ('C', 125), ('D', 126)]) – Nishant Nawarkhede Feb 13 '14 at 09:35
  • No , don't want to subtract `1` from each value , these may not be ordered always ! – Nishant Nawarkhede Feb 13 '14 at 09:41