Combine String in a Dictionary with Similar Key
<p>I am trying to create a new Dictionary based on 3 others dictionary in my python data processing.</p>

<p>I have 3 Dictionaries, each with similar ID representing different section in the document.</p>

<p>For example</p>

<pre><code>dict1 = {'001': 'Dog', '002': 'Cat', '003': 'Mouse'}
dict2 = {'001': 'Dog2', '002': 'Cat2', '003': 'Mouse2'}
dict3 = {'001': 'Dog3', '002': 'Cat3', '003': 'Mouse3'}
</code></pre>

<p>I wanted to combine all the values of similar key, therefore my desire output would like similar to this.</p>

<pre><code>combineDict = {'001' : 'Dog Dog2 Dog3', '002' : 'Cat Cat2 Cat3', '003' : 'Mouse Mouse2 Mouse3'}
</code></pre>

<p>I did this</p>

<pre><code>combineDict = {}
for k in dict1.keys():
    combineDict[k] = dict1[k] + " " + dict2[k] + " " + dict3[k]
</code></pre>

<p>However, the method above is super slow when dealing with large amount of text.</p>

<p>Is there anyway to write this function professionally to give the same result and lowered down the time it takes to process.</p>

<p>Thank you very much :)</p>

<p>To keep in line with your current approach, and specifically binding the following solution to the fact that you always have three equally length dictionaries, the approach is as such: </p>

<p>Iterate using one of the dictionaries, and create a new dictionary that will hold the values as a space separated string. The easiest way to do this is to collect them in a <code>list</code> and then use <code>" ".join</code>, which will give you the space separated list:</p>

<pre><code>dict1 = {'001': 'Dog', '002': 'Cat', '003': 'Mouse'}
dict2 = {'001': 'Dog2', '002': 'Cat2', '003': 'Mouse2'}
dict3 = {'001': 'Dog3', '002': 'Cat3', '003': 'Mouse3'}


new_dict = {}

for key in dict1:
    new_dict[key] = " ".join([dict1[key], dict2[key], dict3[key]])
</code></pre>

<p>Output:</p>

<pre><code>{'001': 'Dog Dog2 Dog3', '003': 'Mouse Mouse2 Mouse3', '002': 'Cat Cat2 Cat3'}
</code></pre>

<p>Or simply as a dictionary comprehension:</p>

<pre><code>res = {k: " ".join([dict1[key], dict2[key], dict3[key]]) for k in dict1}
</code></pre>

python