Select to view content in your preferred language

Merge two dictionaries into one

3433
2
12-08-2021 02:07 PM
ToddLusk
Regular Contributor

I have two dictionaries that I would like to merge into a combined one with the "values" added together (see below).  The dictionaries are the results of "Summary Counts" of two different columns of data in a hosted feature layer.  Here are the dictionaries:

d1 = {"A":10, "B":20, "C":30}

d2 = {"A":1, "B":14, "D":3, "E":5}

I would like to end up with something like:

d3 = {"A":11, "B":34, "C":30, "D":3, "E":3}

As you can see, the dictionary "keys" may not be the same between the two summaries every time.  Ultimately, I want to use the combined summary (i.e., the data in"d3") in a Serial Chart in a Dashboard.  I'm struggling with how to compare the two dictionaries and check for corresponding keys in each.

0 Kudos
2 Replies
jcarlson
MVP Esteemed Contributor

Let's solve this with a custom function! For each key in the input dicts, we need to see if the key already exists. If it doesn't, add it as a new key to the output; if it does, add the values together.

 

var d1 = {"A":10, "B":20, "C":30}
var d2 = {"A":1, "B":14, "D":3, "E":5}

function dict_merge(dicts_array){
    // Empty dict for output
    var out_dict = {}
    
    // Loop over array of input dicts
    for(var dict in dicts_array){

        // Loop over keys in dict
        for(var d in dicts_array[dict]){

            // Add / sum dict value depending on presence of key in out_dict
            if(!HasKey(out_dict, d)){
                out_dict[d] = dicts_array[dict][d]
            } else {
                out_dict[d] += dicts_array[dict][d]
            }
        }
    }
    
    return out_dict
}

dict_merge([d1, d2])

 

And the output:

jcarlson_0-1639018458465.png

The best part is, a custom function like this can be used anywhere else you might need it, and is written in such a way that any number of dicts can be supplied, and the output will still work.

- Josh Carlson
Kendall County GIS
ToddLusk
Regular Contributor

Awesome, thank you so much!  I had the "logic" right in my head but couldn't quite figure out the syntax.

0 Kudos