合并字典列表中相同键的值,并与python3中的另一个字典列表进行比较

时间:2014-03-10 16:52:10

标签: python list python-3.x dictionary combinations

更新:显然,我注意到在我的主代码中,当我从readExpenses.py中提取的词典列表中提取值时,我将其存储为一个集合,而不是字典列表。

现在,我知道我使用以下代码行将每个字典存储在'exp'列表中:

for e in expenses:

    exp.append(e)

但是,我只想要那些字典中的Keys Amount和Type,而不是其他条目。

供参考,以下是费用字典中的键列表:

"Date","Description","Type","Check Number","Amount","Balance"

如前所述,我只需要Type和Amount。

我正在尝试制定预算计划,所以我有这个词典列表:

[{'Bills': 30.0}, {'Bills': 101.53}, {'Bills': 60.0}, {'Bills': 52.45}, {'Gas': 51.17}, {500.0: 'Mortgage'}, {'Food': 5.1}]

我试图将它与这个字典列表进行比较:

[{400.0: 'Bills'}, {'Gas': 100.0}, {500.0: 'Mortgage'}, {'Food': 45.0}]

第一个列表是我在一个月内花在不同服务上的金额,以及它所属的类别,第二个字典是预算允许我在该类别上花费的最大金额。

目标是,在第一个字典中,将同一个键的所有值组合成一个键:值对,然后将其与第二个字典进行比较。

所以我应该从第一个词典中获取这个词典列表:

[{'Bills': 295.15), {'Gas': 51.17}, {500.0: 'Mortgage'}, {'Food': 5.1}]

我尝试查看this examplethis one,但它们只是将字典列表合并在一起,而不是对相同键的值进行求和。我确实尝试了后者的代码,但它只加入了词典。我注意到这笔钱似乎只适用于“原始”字典,而不是字典列表。

我确实尝试过这个想法实验:

print(sum(item['amount'] for item in exp))

我知道这将总结金额以下的所有数字,而不是为每个类别返回一个数字,但是我想尝试一下它,看看它是否会导致解决方案,但我得到了这个错误的回报:

TypeError: 'set' object is not subscriptable

当我搞砸时,Counter函数似乎也显示出一种解决方案的承诺,但它似乎只适用于自己的字典,而不是字典列表。

#where exp is the first dictionary that I mentioned
a = Counter(exp)
b = Counter(exp) 

c = a + b #I'm aware the math would have be faulty on this, but this was a test run
print (c)

此尝试返回此错误:

TypeError: unhashable type: 'set'

另外,有没有办法在不导入集合模块的情况下使用python附带的内容?

我的代码:

from readExpense import *
from budget import *
from collections import *

#Returns the expenses by expenses type
def expensesByType(expenses, budget):

    exp = []

    expByType = []

    bud = []


    for e in expenses:

        entry = {e['exptype'], e['amount']}

        exp.append(entry)

    for b in budget:
        entry = {b['exptype'], b['maxamnt']}

        bud.append(entry)



    return expByType;


def Main():

    budget = readBudget("budget.txt")
    #printBudget(budget)

    expenses = readExpenses("expenses.txt")
    #printExpenses(expenses)

    expByType = expensesByType(expenses, budget)        

if __name__ == '__main__':
    Main()

供参考,分别来自预算和readexpense。

budget.py

def readBudget(budgetFile):
    # Read the file into list lines
    f = open(budgetFile)
    lines = f.readlines()
    f.close()

    budget = []

    # Parse the lines
    for i in range(len(lines)):
        list = lines[i].split(",")

        exptype = list[0].strip('" \n')
        if exptype == "Type":
            continue

        maxamount = list[1].strip('$" \n\r')

        entry = {'exptype':exptype, 'maxamnt':float(maxamount)}

        budget.append(entry)

    return budget

def printBudget(budget):
    print()
    print("================= BUDGET ==================")
    print("Type".ljust(12), "Max Amount".ljust(12))

    total = 0
    for b in budget:
        print(b['exptype'].ljust(12), str("$%0.2f" %b['maxamnt']).ljust(50))
        total = total + b['maxamnt']

    print("Total: ", "$%0.2f" % total)

def Main():
    budget = readBudget("budget.txt")
    printBudget(budget)

if __name__ == '__main__':    
    Main()

readExpense.py

def readExpenses(file):

    #read file into list of lines
    #split lines into fields
    # for each list create a dictionary
    # add dictionary to expense list

    #return expenses in a list of dictionary with fields
    # date desc, exptype checknm, amnt

    f = open(file)
    lines=f.readlines()
    f.close()

    expenses = []

    for i in range(len(lines)):
        list = lines[i].split(",")

        date = list[0].strip('" \n')
        if date == "Date":
            continue

        description = list[1].strip('" \n\r')
        exptype= list[2].strip('" \n\r')
        checkNum = list[3].strip('" \n\r')
        amount = list[4].strip('($)" \n\r')
        balance = list[5].strip('" \n\r')

        entry  ={'date':date, 'description': description, 'exptype':exptype, 'checkNum':checkNum, 'amount':float(amount), 'balance': balance}

        expenses.append(entry)

    return expenses

def printExpenses(expenses):

    #print expenses
    print()
    print("================= Expenses ==================")
    print("Date".ljust(12), "Description".ljust(12), "Type".ljust(12),"Check Number".ljust(12), "Amount".ljust(12), "Balance".ljust(12))

    total = 0

    for e in expenses:
        print(str(e['date']).ljust(12), str(e['description']).ljust(12), str(e['exptype']).ljust(12), str(e['checkNum']).ljust(12), str(e['amount']).ljust(12))
        total = total + e['amount']


    print()

    print("Total: ", "$%0.2f" % total)

def Main():
    expenses = readExpenses("expenses.txt")
    printExpenses(expenses)

if __name__ == '__main__':
    Main()

1 个答案:

答案 0 :(得分:0)

您是否有理由避免创建一些对象来管理它?如果是我,我会去对象并执行以下操作(这是完全未经测试的,可能存在拼写错误):

#!/usr/bin/env python3

from datetime import datetime # why python guys, do you make me write code like this??
from operator import itemgetter

class BudgetCategory(object):
    def __init__(self, name, allowance):
        super().__init__()
            self.name = name # string naming this category, e.g. 'Food'
            self.allowance = allowance # e.g. 400.00 this month for Food
            self.expenditures = [] # initially empty list of expenditures you've made

    def spend(self, amount, when=None, description=None):
        ''' Use this to add expenditures to your budget category'''
        timeOfExpenditure = datetime.utcnow() if when is None else when #optional argument for time of expenditure
        record = (amount, timeOfExpenditure, '' if description is None else description) # a named tuple would be better here...
        self.expenditures.append(record) # add to list of expenditures
        self.expenditures.sort(key=itemgetter(1)) # keep them sorted by date for the fun of it

    # Very tempting to the turn both of the following into @property decorated functions, but let's swallow only so much today, huh?
    def totalSpent(self):
        return sum(t[0] for t in self.expenditures)

    def balance(self):
        return self.allowance - self.totalSpent()

现在我可以使用正确的代码:

budget = BudgetCategory(name='Food', allowance=200)
budget.spend(5)
budget.spend(8)

print('total spent:', budget.totalSpent())
print('left to go:', budget.balance())

这只是一个起点。现在你可以添加通过装饰对支出列表进行分组(和求和)的方法(例如“我上个月在Twinkies上花了多少钱”)。您可以添加一个方法来解析文件中的条目,或将它们发送到csv列表。你可以根据时间做一些图表。