简体   繁体   English

交换字典项目 python

[英]swap dict items python

I am trying to swap items by index inside one python dict, here is my data structure我正在尝试在一个 python 字典中按索引交换项目,这是我的数据结构

{'A': [4, 7], 'B': [5, 1], 'C': [0, 5], 'D': [1, 3], 'E': [3, 0], 'F': [2, 6], 'G': [7, 2], 'H': [6, 4]}

I want to swap items for example like this:我想交换项目,例如:

 {'F': [2, 6], 'B': [5, 1], 'C': [0, 5], 'D': [1, 3], 'E': [3, 0], 'A': [4, 7], 'G': [7, 2], 'H': [6, 4]}

I would convert the dict to a list first:我会先将字典转换为列表:

d = {'A': [4, 7], 'B': [5, 1], 'C': [0, 5], 'D': [1, 3], 'E': [3, 0], 'F': [2, 6], 'G': [7, 2], 'H': [6, 4]}
l = list(d.items())
l[i1], l[i2] = l[i2], l[i1]
d = dict(l)

You can't reorder a dict arbitrarily without rebuilding it (a bunch of targeted pop s and reinsertions could do it piece by piece, but it would be absurdly complicated to little or no benefit).你不能在不重建的情况下任意重新排序dict (一堆有针对性的pop和重新插入可以逐个完成,但它会非常复杂,几乎没有好处)。 If you want to swap the position of two key/value pairs, your best option is to convert to a list of such pairs, swap the indices, then convert back to dict , eg:如果要交换两个key/value对的 position ,最好的选择是转换为此类对的list ,交换索引,然后转换回dict ,例如:

population = {'A': [4, 7], 'B': [5, 1], 'C': [0, 5], 'D': [1, 3], 'E': [3, 0], 'F': [2, 6], 'G': [7, 2], 'H': [6, 4]}
population = list(population.items())
population[indexA], population[indexB] = population[indexB], population[indexA]
population = dict(population)

This is O(n) work to be clear (done once to convert to list , again to convert back to dict );这是O(n)需要明确的工作(一次转换为list ,再次转换回dict ); if you actually need to do it repeatedly, I'd suggest sticking to a list without converting to a dict at all.如果您确实需要重复执行此操作,我建议您坚持使用list而不转换为dict

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM