python - 我如何将 Python 元组转换为字典

标签 python dictionary tuples

为了将 t = [('a', 1), ('b', 2), ('c', 3), ('a', 4)] 转换为字典,我希望输出为 {'a':5,'b':2,'c':3} 而不是 {'a':4,'b':2, 'c':3}。 有没有办法把同一个关键项的值加起来?

我正在使用这一行来转换元组:

dict((x,y) for x, y in t)

最佳答案

我的方法:使用默认值为 0 的 get

t = [('a', 1), ('b', 2), ('c', 3), ('a', 4)]
d = dict()
for x,y in t:
    d[x] = d.get(x, 0) + y;
print(d)

关于python - 我如何将 Python 元组转换为字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57635553/

相关文章:

关于选民投票率的Python分配问题: class and object and function

javascript - 在 MVC 中解析 JSON 字典中的键/值对结果

c++ - 如何找到元组 vector 中的最大值?

Python-将数据帧中的值附加到相应的元组元素

python - 如何调试未调用的 __del__()

python - 类模式匹配错误的情况

Python win32 com : how to handle 'out' parameter?

c# - 从多个 (n) 列表生成所有组合

python - 通过循环使用元组键创建字典

scala - 将 RDD[(Long,Long)] 转换为 RDD[Row]