python - 其键独立于它包含的元素顺序的字典

标签 python dictionary key tuples

我想在 Python 中创建一个字典,其键将独立于它包含的元素的顺序。这是示例:

items = {1: 2, 2: 3, 4: 5}
comb = {(key1, key2): 0 for key2 in items.keys() for key1 in items.keys() if key1 != key2}

输出:

{(1, 2): 0, (1, 4): 0, (2, 1): 0, (4, 2): 0, (4, 1): 0, (2, 4): 0}

但我只想拥有:

{(1, 2): 0, (1, 4): 0, (2, 4): 0}

所以键 (1, 2) 应该等于 (2, 1)。对于长度超过 2 的元组(例如 (2, 3, 4) = (4, 3, 2)),这也需要成立。

最佳答案

使用 itertools.combinations :

>>> {keys: 0 for keys in itertools.combinations(items, 2)}
{(1, 2): 0, (2, 4): 0, (1, 4): 0}

dict.fromkeys (仅当值不可变时才使用 dict.fromkeys;该值由所有条目共享):

>>> dict.fromkeys(itertools.combinations(items, 2), 0)
{(1, 2): 0, (2, 4): 0, (1, 4): 0}

>>> dict.fromkeys(itertools.combinations(items, 3), 0)
{(1, 2, 4): 0}

关于python - 其键独立于它包含的元素顺序的字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21202429/

相关文章:

python - 如何有效地将数组解码为 pandas 数据框中的列

python - Kmeans 不知道集群的数量?

c++ - 什么可以使 std::map 找不到它的键之一?

java - MAP Keyset 不工作 - 无法识别关键字 KeyType?

c# - 为什么 IDictionary<TKey, TValue> 扩展 ICollection<KeyValuePair<TKey, TValue>>?

java - java keyhandler 中的键盘灵敏度较低?

python - 如何安装 libavformat.so.56 和 libavformat.so.57?

python - 使用具有不同项目大小的 Py_buffer 和 PyMemoryView_FromBuffer

ios - 如何从文件中恢复 RSA?

php - 在 Twig 中使用 merge() 时键值被 'key' 替换