简体   繁体   中英

Is there a way to combine common keys and add values in Python?

Hi there ive seen various posts on how to combine two dictionaries in Python, However what I would like to do is combine like keys in the same dictionary and add the values? ..in truth what i will do initially is rename the keys into various categories and then id like to combine similar keys and add the values. is there a simple method to make this possible? at the moment ive opted for iterating and changing keys..but this seems a slow way of doing things. im wondering whether or not to iterate over transaction description first and create a new list then zip or not? any ideas apprecaited thanks.

here is my modest start

df = pd.read_csv("spreadsheet.csv")
item = df['Transaction Description']
cost = df['Debit Amount']

purchases = {}

purchases = {}
key, value in zip(item, cost):
purchases[key] = value


keys = purchases.keys()


 for i in purchaces.keys {
  if key == "Soverign housing" 
  purchases [Rent] = purchaces[Soverign housing]
 del dictionary[Soverign housing]
 ...etc

The simplest is to use in to see if a new dictionary contains a key from each dictionary, in this example i used *args which is the list of the arguments to make it more flexible.

dic_a = {'A': 20, 'B': 30, 'C': 40}
dic_b = {'A': 5, 'C': 2, 'F': 100}
dic_c = {'H': 32, 'K': 75, 'G': 15}

def combine_dict(*args):
    comb = dict()
    for dic in args:
        for key in dic:
            if key in comb:
                comb[key] += dic[key]
            else:
                comb[key] = dic[key]
    return comb

if __name__ == '__main__':
    print(combine_dict(dic_a, dic_b))
    print(combine_dict(dic_a, dic_b, dic_c))

I don't understand what does your mean about condensed values etc.

@user1717828 is Right for asking input/Out code so we can understand it clearly.

But how much i understand is that you want when you combine 2 dict object it should keep same keys but combine Values eg

dict_a = {'A':1, 'B': 2, 'C':3}
dict_b = {'A':10, 'C': 20, 'D':30}

for key,val in dict_b:
    try:
        _key = dict_a[key]  # Already Exist Key in Dict A
    except: # If Object does not Exist
        dict_a[key]=val
    else: # If exist Then Make a list and Append
        dict_a_val = dict_a[key] #Current value in dict_a
        dict_a[key] = []
        dict_a[key].append(dict_a_val)
        dict_a[key].append(val)

#output:
# {'A':[1,10], 'B': 2, 'C':[3,20] , 'D':30}

Hope you were looking for this

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM