如何修复反向键与值列表理解也随机化索引?

2024-09-26 22:51:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个原始的格言:

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没有帮助

我该怎么做?你知道吗


Tags: innewformydict键值key2key1
1条回答
网友
1楼 · 发布于 2024-09-26 22:51:22

您可以使用Orderdict:

my_dict=OrderedDict([('key1', 'value1'), ('key2', 'value2'), ('key3', 'value3')])

for k, v in my_dict.items():
    new_dict.update({v: k})
print(new_dict)

您将获得value:key订单信息:

OrderedDict([('value1', 'key1'), ('value2', 'key2'), ('value3', 'key3')])

在python3.6中dict有序的(在CPython实现下)。你知道吗

dict() now uses a “compact” representation pioneered by PyPy. The memory usage of the new dict() is between 20% and 25% smaller compared to Python 3.5. PEP 468 (Preserving the order of **kwargs in a function.) is implemented by this. The order-preserving aspect of this new implementation is considered an implementation detail and should not be relied upon (this may change in the future, but it is desired to have this new dict implementation in the language for a few releases before changing the language spec to mandate order-preserving semantics for all current and future Python implementations; this also helps preserve backwards-compatibility with older versions of the language where random iteration order is still in effect, e.g. Python 3.5). (Contributed by INADA Naoki in issue 27350. Idea originally suggested by Raymond Hettinger.)

顺便说一下,如果您需要顺序,并且想要反转key/value,为什么不尝试元组列表,这样您就不必担心重复键的问题了:

[ (k1,v1), (k2,v2) ]

希望这有帮助。你知道吗

相关问题 更多 >

    热门问题