首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >合并字典列表中相同键的值,并与python3中的另一个字典列表进行比较

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

Stack Overflow用户
提问于 2014-03-10 16:52:10
回答 1查看 987关注 0票数 0

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

现在,我知道我将每个字典存储在'exp‘列表中,其中包含以下代码:

代码语言:javascript
复制
for e in expenses:

    exp.append(e)

但是,我只想从这些字典中输入键的数量,而不是其他条目。

作为参考,下面是费用字典中的键列表:

代码语言:javascript
复制
"Date","Description","Type","Check Number","Amount","Balance"

如前所述,我只需要类型和数量。

我正试图制定一个预算计划,所以我有一个字典清单:

代码语言:javascript
复制
[{'Bills': 30.0}, {'Bills': 101.53}, {'Bills': 60.0}, {'Bills': 52.45}, {'Gas': 51.17}, {500.0: 'Mortgage'}, {'Food': 5.1}]

我试着把它和这一系列字典进行比较:

代码语言:javascript
复制
[{400.0: 'Bills'}, {'Gas': 100.0}, {500.0: 'Mortgage'}, {'Food': 45.0}]

第一个列表是我一个月在不同的服务上花了多少钱,它属于什么类别,第二个字典是预算允许我在这个类别上花费的最大金额。

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

所以我应该把第一本字典列出来:

代码语言:javascript
复制
[{'Bills': 295.15), {'Gas': 51.17}, {500.0: 'Mortgage'}, {'Food': 5.1}]

我试着查看这个例子这一个,但它们只是将字典列表合并在一起,而不是将相同键的值相加。我确实尝试了后者的代码,但它只是将字典连接在一起。我注意到sum似乎只适用于“原始”字典,而不适用于字典列表。

我确实尝试过这是一个思考实验:

代码语言:javascript
复制
print(sum(item['amount'] for item in exp))

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

代码语言:javascript
复制
TypeError: 'set' object is not subscriptable

当我到处乱跑的时候,计数器函数似乎也显示了它作为解决方案的前景,然而,它似乎只适用于独立的字典,而不适用于字典列表。

代码语言:javascript
复制
#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)

此尝试返回此错误:

代码语言:javascript
复制
TypeError: unhashable type: 'set'

另外,是否有一种不导入集合模块并使用python附带的功能的方法?

我的代码:

代码语言:javascript
复制
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()

并可供参考,分别从预算和阅卷两方面进行编码。

budget.py

代码语言:javascript
复制
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

代码语言:javascript
复制
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()
EN

回答 1

Stack Overflow用户

发布于 2014-03-10 17:32:21

你为什么要避免创建一些对象来管理它呢?如果是我,我会选择对象并执行如下操作(这是完全未经测试的,可能有打字):

代码语言:javascript
复制
#!/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()

现在,我可以正确地编写如下代码:

代码语言:javascript
复制
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列表中。你可以根据时间绘制一些图表。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22306340

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档