字典在python2和python3中如何以及为什么不同?

时间:2015-11-19 17:01:48

标签: python string dictionary hash cpython

作为一项实验,python2python3中的哈希值似乎不同:

alvas@ubi:~$ python -c "from collections import Counter; x = Counter({'foo': 1, 'bar': 1, 'foobar': 1, 'barfoo': 1}); print(x.most_common())"
[('foobar', 1), ('foo', 1), ('bar', 1), ('barfoo', 1)]
alvas@ubi:~$ python -c "from collections import Counter; x = Counter({'foo': 1, 'bar': 1, 'foobar': 1, 'barfoo': 1}); print(x.most_common())"
[('foobar', 1), ('foo', 1), ('bar', 1), ('barfoo', 1)]
alvas@ubi:~$ python -c "from collections import Counter; x = Counter({'foo': 1, 'bar': 1, 'foobar': 1, 'barfoo': 1}); print(x.most_common())"
[('foobar', 1), ('foo', 1), ('bar', 1), ('barfoo', 1)]


alvas@ubi:~$ python3 -c "from collections import Counter; x = Counter({'foo': 1, 'bar': 1, 'foobar': 1, 'barfoo': 1}); print(x.most_common())"
[('barfoo', 1), ('foobar', 1), ('bar', 1), ('foo', 1)]
alvas@ubi:~$ python3 -c "from collections import Counter; x = Counter({'foo': 1, 'bar': 1, 'foobar': 1, 'barfoo': 1}); print(x.most_common())"
[('foo', 1), ('barfoo', 1), ('bar', 1), ('foobar', 1)]
alvas@ubi:~$ python3 -c "from collections import Counter; x = Counter({'foo': 1, 'bar': 1, 'foobar': 1, 'barfoo': 1}); print(x.most_common())"
[('bar', 1), ('barfoo', 1), ('foobar', 1), ('foo', 1)]

当我们查看字符串哈希时,python3哈希似乎是动态的:

alvas@ubi:~$ python -c "print 'abc'.__hash__()"
1453079729188098211
alvas@ubi:~$ python -c "print 'abc'.__hash__()"
1453079729188098211
alvas@ubi:~$ python -c "print 'abc'.__hash__()"
1453079729188098211


alvas@ubi:~$ python3 -c "print ('abc'.__hash__())"
-4165906745021293940
alvas@ubi:~$ python3 -c "print ('abc'.__hash__())"
-4676677077013862663
alvas@ubi:~$ python3 -c "print ('abc'.__hash__())"
5261896652811750722

我的问题是为什么以及哈希是如何不同的?

他们每个人使用哪种哈希算法?我在哪里找到字符串哈希发生的确切CPython代码?

有没有办法取消随机化哈希?

EDITED

阅读PEP398后,可以取消设置随机哈希,但由于安全问题,不建议使用。

alvas@ubi:~$ export PYTHONHASHSEED=0
alvas@ubi:~$ python3 -c "print ('abc'.__hash__())"
4596069200710135518
alvas@ubi:~$ python3 -c "print ('abc'.__hash__())"
4596069200710135518
alvas@ubi:~$ python3 -c "print ('abc'.__hash__())"
4596069200710135518

0 个答案:

没有答案