将元组列表中的重复项合并到对值求和的字典中

Incorporate duplicates in a list of tuples into a dictionary summing the values

您好,我想将这个元组列表转换成字典。由于我是 python 的新手,我正在想办法转换成字典。如果只有一个值,我只能转换成字典。就我而言,it.I 中有两个值将在下面详细说明:

    `List of tuples: [('Samsung', 'Handphone',10), ('Samsung', 'Handphone',-1),
('Samsung','Tablet',10),('Sony','Handphone',100)]`

正如您在上面看到的,我希望将 'Samsung' 标识为键,将 'Handphone' 和“10”标识为与键相关的值。

我想要的输出是:

  `Output: {'Sony': ['Handphone',100], 'Samsung': ['Tablet',10,'Handphone', 9]}`

正如您在上面看到的,项目 'handphone' 和 'tablet' 是根据键值分组的,在我的例子中是 Sony 和 Samsung。如果它们属于相同的项目和相同的密钥(三星或索尼),则增加/减少项目的数量。

非常感谢你们为实现上述输出而提出的任何建议和想法。我真的运行没思路了。谢谢你。

你可以通过字典理解来做到这一点

您真正想要的是元组键,这将是公司和设备。

tuples = [('Samsung', 'Handphone',10), 
          ('Samsung', 'Handphone',-1),
          ('Samsung','Tablet',10),
          ('Sony','Handphone',100)]

d = {}
for company, device, n in tuples:
    key = (company, device)
    d[key] = d.get(key, 0) + n

defaultdict

的好机会
from collections import defaultdict

the_list = [
    ('Samsung', 'Handphone', 10), 
    ('Samsung', 'Handphone', -1), 
    ('Samsung', 'Tablet', 10),
    ('Sony', 'Handphone', 100)
]

d = defaultdict(lambda: defaultdict(int))

for brand, thing, quantity in the_list:
    d[brand][thing] += quantity

结果将是

{
    'Samsung': {
        'Handphone': 9, 
        'Tablet': 10
    },
    'Sony': {
        'Handphone': 100
    }
}

你的输出有问题,可以通过正确的标识看到:

{
    'Sony': ['Handphone',100], 
    'Samsung': ['Tablet',10],
    ['Handphone', 9]
}

手机不是'Samsung'的一部分,你可以做一个list of lists来得到:

{
    'Sony': [
        ['Handphone',100]
    ],
    'Samsung': [
        ['Tablet',10],
        ['Handphone', 9]
    ]
}

有:

my_list = [('Samsung', 'Handphone',10), ('Samsung', 'Handphone',-1), ('Samsung','Tablet',10),('Sony','Handphone',100)]

result = {}
for brand, device, value in my_list:
    # first verify if key is present to add list for the first time
    if not brand in result:
        result[brand] = []
    # then add new list to already existent list
    result[brand] += [[device, value]]

但我认为最好的格式是字典:

{
    'Sony': {
        'Handphone': 100
    },
    'Samsung': {
        'Tablet': 10,
        'Handphone': 9
    }
}

那就是:

my_list = [('Samsung', 'Handphone',10), ('Samsung', 'Handphone',-1), ('Samsung','Tablet',10),('Sony','Handphone',100)]

result = {}
for brand, device, value in my_list:
    # first verify if key is present to add dict for the first time
    if not brand in result:
        result[brand] = {}
    # then add new key/value to already existent dict
    result[brand][device] = value