Suppose I have two arrays:
arrayOne = [["james", 35], ["michael", 28], ["steven", 23],
["jack", 18], ["robert", 12]]
arrayTwo = [["charles", 45], ["james", 36], ["trevor", 24],
["michael", 17], ["steven", 4]]
I want to merge them, so that I would have a single 2D array, where the first element of each inner array is the name (james, charles, etc). The second element of the inner array is its respective value in arrayOne, and if does not have a respective value it would be 0. Conversely for the third element. The order does not really matter as long as the numbers match the name. In other words I would get something like this
arrayResult = [["james", 35, 36], ["michael", 28, 17], ["steven", 23, 4],
["jack", 18, 0], ["robert", 12, 0], ["charles", 0, 45],
["trevor", 0, 4]]
Also, I am trying to have it so that I could add more “columns” to this array result if I were to give another array.
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:
From there, you can put them together like this:
What this does is create a new dictionary called
combined, 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 thecombineddictionary, telling calls to the.getmethod to supply0if no value is present. If you need to switch the combined dictionary back to an array, that’s pretty easy too: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:
If you wanted to encapsulate all this logic in a function (which is something I would recommend), you could do it like this: