元组到字典并从Python字典中删除重复键但总结值

时间:2016-03-07 13:08:38

标签: python python-3.x

我的python函数有以下结果。

('bread', '$1.90')
('bread', '$1.95')
('chips', '$2.54')
('milk', '$2.31')
('milk', '$2.38')

现在我想制作一个字典或列表,如下面没有重复键,但是有求和值。

[('bread', '$3.85'), ('chips', '$2.54'), ('milk', '$7.04')]

我的Python版本是3.5。

5 个答案:

答案 0 :(得分:3)

使用collections.defaultdict

from collections import defaultdict
s = [('bread', '$1.90'), ('bread', '$1.95'), ('chips', '$2.54'), ('milk', '$2.31'), ('milk', '$2.38')]
d = defaultdict(str)
for k, v in s:
    price = float(d[k][1:]) if d[k] else 0.0
    price += float(v[1:])
    d[k] = '${}'.format(price)

请注意,将价格总和存储为字符串可能会导致值不正确。更正确的方法是使用一个只对浮点数求和的类(没有转换str / float)并将结果显示为字符串。

答案 1 :(得分:1)

我想不是最优雅的方式,但是:

{'milk': 4.69, 'chips': 2.54, 'bread': 3.85}

给予:

WSGIPythonPath /path/to/mysite.com

答案 2 :(得分:0)

你可以做到

tuples = [('bread', '$1.90'),
    ('bread', '$1.95'),
    ('chips', '$2.54'),
    ('milk', '$2.31'),
    ('milk', '$2.38')]
prices = dict()

for t in tuples:
    try:
        prices[t[0]] += float(t[1][1:])
    except KeyError:
        prices[t[0]] = float(t[1][1:])

在dict中,价格不会有'$'

答案 3 :(得分:0)

您可以执行以下操作。

#encoding:UTF-8
import re

info = dict()
tuple=(('bread', '$1.90'),('bread', '$1.95'),('chips', '$2.54'),('milk', '$2.31'),('milk', '$2.38'))
for index in range(len(tuple)):
    s=re.findall(r'(\d+\.\d+)', tuple[index][1])[0]
    m=tuple[index][0]
    if(info.has_key(m))
        i=info[m]+s
        info[m]=i
    else
        info[m]=s


print info

答案 4 :(得分:0)

解决此问题的简便方法:

#first you made a list of tuples from splitting lines as item, price
    tuple_out = [('bread', 1.90), 
                ('chips  ',  2.54), 
                ('chocolate', 20), 
                ('chocolate ', 1.95), 
                ('goods', 2.31), 
                ('insurance', 110), 
                ('loan', 195), 
                ('goods   ', 2.31),
                ('insurance', 110), 
                ('milk', 2.35),
                ('loan', 195)]

#then made a dictionary removing duplicate items with adding corresponding price to the item

    result = {}
    for k, v in tuple_out:
      result[k.strip()] = result.get(k.strip(), 0) + v
    # format dictionary as per requirement
    # here I add $ and limit up to 2 digits after decimal
    dic={}
    for k,v in result.items():
        dic[k]='${0:.2f}'.format(round(v,2))
    # convert dictionary to list and sort list
    L=([(k,v) for k, v in dic.iteritems()])
    L.sort()
    #print list of tuples
    print(L)

希望这会有所帮助。