将同一个键的值合并到字典列表中,并与python3中的另一个字典列表进行比较
更新:显然,我注意到在我的主代码中,当我从readExpenses.py获取的字典列表中提取值时,我将其存储为一个集合,而不是一个字典列表 现在,我知道我将每个字典存储在“exp”列表中,其中包含以下代码行:将同一个键的值合并到字典列表中,并与python3中的另一个字典列表进行比较,python,list,python-3.x,dictionary,combinations,Python,List,Python 3.x,Dictionary,Combinations,更新:显然,我注意到在我的主代码中,当我从readExpenses.py获取的字典列表中提取值时,我将其存储为一个集合,而不是一个字典列表 现在,我知道我将每个字典存储在“exp”列表中,其中包含以下代码行: for e in expenses: exp.append(e) 但是,我只需要这些字典中的键数量和类型,而不需要其他条目 以下是费用字典中的关键字列表,以供参考: "Date","Description","Type","Check Number","Amount","Bal
for e in expenses:
exp.append(e)
但是,我只需要这些字典中的键数量和类型,而不需要其他条目
以下是费用字典中的关键字列表,以供参考:
"Date","Description","Type","Check Number","Amount","Balance"
如前所述,我只需要类型和数量
我正试图制定一个预算计划,因此我有以下词典列表:
[{'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': 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}]
我试着查看和,但它们只是将字典列表合并在一起,而不是对同一个键的值求和。我确实在后者中尝试了代码,但它只是将字典连接在一起。我注意到sum似乎只适用于“原始”词典,而不适用于词典列表
#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)
我确实尝试过这个作为一个思想实验:
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'
另外,有没有一种方法可以不用导入collections模块,也不用使用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()
您避免创建一些对象来管理它有什么原因吗?如果是我,我会选择对象并执行以下操作(这是完全未经测试的,可能会有拼写错误): 现在我可以更正如下代码:
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列表。你可以根据时间做一些图表。你没有字典列表,你有集合列表。更改为
[{'Bills':30.0},{'Bills':101.53},…]
(注意冒号)并重新开始。