Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>It looks like what you really need is dictionaries, rather than arrays. If you use a dictionary, this problem becomes a whole lot easier. Converting to dicts couldn't be easier: </p> <pre><code>dictOne = dict(arrayOne) dictTwo = dict(arrayTwo) </code></pre> <p>From there, you can put them together like this:</p> <pre><code>combined = dict() for name in set(dictOne.keys() + dictTwo.keys()): combined[name] = [ dictOne.get(name, 0), dictTwo.get(name, 0) ] </code></pre> <p>What this does is create a new dictionary called <code>combined</code>, which we'll put the final data in. Then, we make a set of keys from both original dictionaries. Using a set ensures we don't do anything twice. Finally, we loop through this set of keys and add each pair of values to the <code>combined</code> dictionary, telling calls to the <code>.get</code> method to supply <code>0</code> if no value is present. If you need to switch the combined dictionary back to an array, that's pretty easy too: </p> <pre><code>arrayResult = [] for name in combined: arrayResult.append([ name ] + combined[name]) </code></pre> <p>Supposing you want to add another column to your result dictionary, all you have to do is change the middle code to look like this:</p> <pre><code>combined = dict() for name in set(dictOne.keys() + dictTwo.keys() + dictThree.keys()): combined[name] = [ dictOne.get(name, 0), dictTwo.get(name, 0), dictThree.get(name, 0) ] </code></pre> <p>If you wanted to encapsulate all this logic in a function (which is something I would recommend), you could do it like this:</p> <pre><code>def combine(*args): # Create a list of dictionaries from the arrays we passed in, since we are # going to use dictionaries to solve the problem. dicts = [ dict(a) for a in args ] # Create a list of names by looping through all dictionaries, and through all # the names in each dictionary, adding to a master list of names names = [] for d in dicts: for name in d.keys(): names.append(name) # Remove duplicates in our list of names by making it a set names = set(names) # Create a result dict to store results in result = dict() # Loop through all the names, and add a row for each name, pulling data from # each dict we created in the beginning for name in names: result[name] = [ d.get(name, 0) for d in dicts ] # Return, secure in the knowledge of a job well done. :-) return result # Use the function: resultDict = combine(arrayOne, arrayTwo, arrayThree) </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload