Home > Net >  Sum of values in a dictionary if part of key is contained in another key
Sum of values in a dictionary if part of key is contained in another key

Time:02-26

Given a dictionary, I want the sum of the values of Node 1 with Bank 1, Node 2 with Bank 2 and so on.

data1 = {"Node 1": 256,"Node 2":25,"Bank 1":16,"Bank 2":20}

Expected Output: 272 45

CodePudding user response:

I'm working under the assumption that all your values look exactly like that

You can first split your nodes and banks

nodes = {k:v for k,v in data1.items() if k.startswith('Node')}
banks = {k:v for k,v in data1.items() if k.startswith('Bank')}

Then just sum the values of the arrays

np.array(list(nodes.values()))   np.array(list(banks.values()))

CodePudding user response:

If all your dictionary will contain are banks and nodes (and without duplicates or missing values), this is easy.

  1. Get the number n of pairs (which is half the number of elements in the dictionary).
  2. Use a for loop with n iterations.
  3. In each iteration, index the values you need and add them up.

Here is an example to get them as a list.

from json import dumps
data1 = {"Node 1": 256, "Node 2": 25, "Bank 1": 16, "Bank 2": 20}

sums = [0] * len(data1) // 2

for i, sum in enumerate(sums):
    sums[i] = data1[f"Node {i   1}"]   data1[f"Bank {i   1}"]

print(sums)

NOTE: It's ususally un-Pythonic to use an index for lists, but I think this is a really straightforward answer to your question.

CodePudding user response:

This code will sum all the matching Node-Bank pairs and ignore the rest.

data1 = {"Node 1": 256,"Node 2":25, "Bank 1":16,"Bank 2":20}

keys = set([key if "Node" in key else "" for key in list(data1.keys())])
keys.remove("")

for key in keys:
    if "Bank "   str(key.split(" ")[1]) in data1.keys():
        print(data1[key]   data1["Bank "   str(key.split(" ")[1])], end=" ")
  • Related