我是Python的初学者。不知道如何在词典中设置顺序? 。我搜寻了一下,发现可以通过from collections import OrderedDict
完成,但不知道如何使用。我正在尝试使用下面提到的代码来比较两个Dictionary,但是我没有按顺序获取输出。
d = { k[0]: k[1:] for k in a }
d2= { k[0]: k[1:] for k in b }
p = {i:j for i,j in d2.items() if i not in d}
q = {i:j for i,j in d.items() if i not in d2}
有什么想法吗?
更新的问题:
i have a nested list . How to get each list of nested list in next line ?
[['Eth116/1/12 sales connected 1 full 10G Fabric Exte'], ['Eth116/1/13 marketing connected 190 full 100 ']]
预期输出:
Eth116/1/12 sales connected 1 full 10G Fabric Exte
Eth116/1/13 marketing connected 190 full 100
答案 0 :(得分:1)
字典是无序的,除了编写dict
自己的子类(不建议)以外,您无法做很多改变。如hiro主人公的评论所示,只要您记住OrderedDict
中的顺序是插入顺序,并且与{{1}键的值。 (Python 3 OrderedDict
的顺序也是如此。)如果dict
和a
具有相同的元素,但顺序不同,则所得的b
将不相等,除非您事先对OrderedDict
和a
进行排序。
如果要比较无法轻易确定插入顺序的两个b
,则需要一个支持无序比较的数据结构。我没有您的数据,所以我不得不补一些数据。我从此输入开始
dict
如您所见,>>> a
[[1, 3, 5, 7, 9], [4, 9, 14, 19, 24, 29, 34, 39], [8, 17, 26, 35, 44, 53, 62, 71], [9, 19, 29, 39, 49, 59, 69, 79, 89]]
>>> b
[[1, 3, 5, 7, 9], [4, 9, 14, 19, 24, 29, 34, 39], [8, 17, 26, 35, 44, 53, 62, 71]]
从a
开始有一个额外的元素。
修改字典构造代码以使值元组不列出,因为dict值需要可哈希才能进行下一步:
9
然后,您可以将字典转换为集合以进行无序比较:
>>> d = { k[0]: tuple(k[1:]) for k in a }
>>> d2= { k[0]: tuple(k[1:]) for k in b }
您可以使用set运算符来发现不同之处:
>>> s = set(d.items())
>>> s2 = set(d2.items())
>>> s == s2
False