我有一个字典,我按特定顺序声明,并希望始终保持该顺序.键/值不能根据它们的值按顺序保存,我只是按照我声明的顺序想要它.
所以,如果我有字典:
d = {'ac': 33, 'gw': 20, 'ap': 102, 'za': 321, 'bs': 10}
Run Code Online (Sandbox Code Playgroud)
如果我查看它或迭代它,它是不是按顺序,有没有办法确保Python将保持我声明键/值的显式顺序?
它看起来像返回的列表keys()和values()字典的方法总是一对一的映射(假设字典在调用2方法之间没有改变).
例如:
>>> d = {'one':1, 'two': 2, 'three': 3}
>>> k, v = d.keys(), d.values()
>>> for i in range(len(k)):
print d[k[i]] == v[i]
True
True
True
Run Code Online (Sandbox Code Playgroud)
如果你不改变调用keys()和调用之间的字典values(),假设上面的for循环总是打印True是错误的吗?我找不到任何证明这一点的文件.
我正在努力有效地改变:
[{'text': 'hallo world', 'num': 1},
{'text': 'hallo world', 'num': 2},
{'text': 'hallo world', 'num': 1},
{'text': 'haltlo world', 'num': 1},
{'text': 'hallo world', 'num': 1},
{'text': 'hallo world', 'num': 1},
{'text': 'hallo world', 'num': 1}]
Run Code Online (Sandbox Code Playgroud)
到没有重复的字典列表和重复的计数:
[{'text': 'hallo world', 'num': 2, 'count':1},
{'text': 'hallo world', 'num': 1, 'count':5},
{'text': 'haltlo world', 'num': 1, 'count':1}]
Run Code Online (Sandbox Code Playgroud)
到目前为止,我有以下内容来查找重复项:
result = [dict(tupleized) for tupleized in set(tuple(item.items()) for item in li)]
Run Code Online (Sandbox Code Playgroud)
它返回:
[{'text': 'hallo world', 'num': 2},
{'text': 'hallo world', 'num': 1},
{'text': 'haltlo …Run Code Online (Sandbox Code Playgroud)