python - 字典中的元组

标签 python dictionary tuples

是否可以在 python 中将元组作为值添加到字典中?
如果是,那么我们如何添加新值呢?我们如何删除和更改它?

最佳答案

>>> a = {'tuple': (23, 32)}
>>> a
{'tuple': (23, 32)}
>>> a['tuple'] = (42, 24)
>>> a
{'tuple': (42, 24)}
>>> del a['tuple']
>>> a
{}

如果您打算使用元组作为键,您可以这样做:

>>> b = {(23, 32): 'tuple as key'}
>>> b
{(23, 32): 'tuple as key'}
>>> b[23, 32] = 42
>>> b
{(23, 32): 42}

一般来说,字典中的元组没有什么特别之处,它们一直表现为元组。

关于python - 字典中的元组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1784973/

相关文章:

python - 合并两个字典并保留第一个字典的值

python - 在具有列表作为值的 python 字典中查找最低值或最少的项目

scala - 光滑的错误 : type TupleXX is not a member of package scala (XX > 22)

Python - 字符串和 now() 的时间增量

python - 如何在运行时将字符串转换为格式化字符串文字?

.net - 为什么不能序列化 Dictionary<key,value>?或者可以吗?

haskell - 元组列表的类型构造函数是什么?

python - 如何从列中获取值并将它们发送到行?

Python:结合使用 astropy.io.fits.open 和 Tensorflow tf.data.Dataset

python - 将列表转换为元组列表,每个元组中的项目具有重复值