我有一个原始的格言:
my_dict = {'key1':''value1',
'key2':'value2',
'key3':'value3'}
在此基础上生成其反向键值,如下所示:
new_dict = {v: k for k, v in my_dict.iteritems()}
它会将键交换为值,但它不会保持“有序顺序”,而是像这样切换索引:
new_dict = {'key3':''value3',
'key2':'value2',
'key1':'value1'}
对我来说,他们必须待在同一地点。你知道吗
我试过做collections.OrderedDict()
,但对生成反向dict没有帮助
我该怎么做?你知道吗
您可以使用Orderdict:
您将获得
value:key
订单信息:在python3.6中
dict
是有序的(在CPython实现下)。你知道吗顺便说一下,如果您需要顺序,并且想要反转
key/value
,为什么不尝试元组列表,这样您就不必担心重复键的问题了:希望这有帮助。你知道吗
相关问题 更多 >
编程相关推荐