Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sum up values based on two dicts with same keys

I have a Python dictionary like {'user_id': 'user_checkpoint'}

checkpoints_dict= {"id_11": "checkpoint_a", "id_13": "checkpoint_a", "id_15": 
                   "checkpoint_b", "id_22": "checkpoint_c", "id_99": "checkpoint_c", 
                   "id_4": "checkpoint_d", "id_2": None}

>>> checkpoints_dict 
>>> {'id_11': 'checkpoint_a',
     'id_13': 'checkpoint_a',
     'id_15': 'checkpoint_b',
     'id_2': None,
     'id_22': 'checkpoint_c',
     'id_4': 'checkpoint_d',
     'id_99': 'checkpoint_c'}

Note: a user might have no checkpoint like id_2!

I have a second dictionary like {'user_id': time}:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

user_time = {"id_11": 40, "id_13": 95, "id_15": 150, "id_22": 12, 
             "id_4": 154, "id_99": 111 , "id_2": 24, "id_3": 43, "id_5": 65, "id_6": 45}

Note: Each user_id from checkpoints_dict can be found within user_time

How do I get the added user_time for each checkpoint within checkpoints_dict? Based on the example I would expect sth. like this:

result_checkpoint_time = {"checkpoint_a": sum([40, 95]),
                          "checkpoint_b": sum([150]),
                          "checkpoint_c": sum([12, 111]),
                          "checkpoint_d": sum([154])}

Since I have no smart idea to approach this I can’t show my solutions to this problem!

>Solution :

You just need to use the user_time dict on the id you get while iterating over the checkpoint dict:

checkpoints_dict = {
    "id_11": "checkpoint_a",
    "id_13": "checkpoint_a",
    "id_15": "checkpoint_b",
    "id_22": "checkpoint_c",
    "id_99": "checkpoint_c",
    "id_4": "checkpoint_d",
    "id_2": None,
}
user_time = {
    "id_11": 40,
    "id_13": 95,
    "id_15": 150,
    "id_22": 12,
    "id_4": 154,
    "id_99": 111,
    "id_2": 24,
    "id_3": 43,
    "id_5": 65,
    "id_6": 45,
}

So:

result = {}
for id_, checkpoint in checkpoints_dict.items():
    if checkpoint is not None:
        result[checkpoint] = result.get(checkpoint, 0) + user_time[id_]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading