OrderedDict Python中的交换值和键

时间:2014-02-13 09:20:20

标签: python python-2.7 ordereddictionary

这是我的OrderedDict

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

我如何将其键和值互换为

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

1 个答案:

答案 0 :(得分:3)

使用zipitertools.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)])

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