Calculating similarity "score" between multiple dictionaries
<p>I have a reference dictionary, "dictA" and I need to compare it (calculate similarity between key and vules) to n amount of dictionaries that are generated on the spot. Each dictionary has the same length. Lets say for the sake of the discussion that the n amount of dictionaries to compare it with is 3: dictB, dictC, dictD.</p>

<p>Here is how dictA looks like:</p>

<pre><code>dictA={'1':"U", '2':"D", '3':"D", '4':"U", '5':"U",'6':"U"}
</code></pre>

<p>Here are how dictB,dictC and dictD look like:</p>

<pre><code>dictB={'1':"U", '2':"U", '3':"D", '4':"D", '5':"U",'6':"D"}
dictC={'1':"U", '2':"U", '3':"U", '4':"D", '5':"U",'6':"D"}
dictD={'1':"D", '2':"U", '3':"U", '4':"U", '5':"D",'6':"D"}
</code></pre>

<p>I have a solution, but just for the option of two dictionaries:</p>

<pre><code>sharedValue = set(dictA.items()) &amp; set(dictD.items())
dictLength = len(dictA)
scoreOfSimilarity = len(sharedValue)
similarity = scoreOfSimilarity/dictLength
</code></pre>

<p>My questions is:
How can I iterate through n amount of dictionaries with dictA being a primary dictionary which I compare others with. The goal is to get a "similarity" value for each dictionary I am gonna iterate through against the primary dictionary. </p>

<p>Thanks for your help.</p>

<p>Here's a general structure -- assuming that you can generate the dictionaries individually, using each before generating the next.  This sounds like what you might want.  calculate_similarity would be a function containing your "I have a solution" code above.</p>

<pre><code>reference = {'1':"U", '2':"D", '3':"D", '4':"U", '5':"U",'6':"U"}
while True:
    on_the_spot = generate_dictionary()
    if on_the_spot is None:
        break
    calculate_similarity(reference, on_the_spot)
</code></pre>

<p>If you need to iterate through dictionaries already generated, then you have to have them in an iterable Python structure.  As you generate them, create a list of dictionaries:</p>

<pre><code>victim_list = [
    {'1':"U", '2':"U", '3':"D", '4':"D", '5':"U",'6':"D"},
    {'1':"U", '2':"U", '3':"U", '4':"D", '5':"U",'6':"D"},
    {'1':"D", '2':"U", '3':"U", '4':"U", '5':"D",'6':"D"}
]
for on_the_spot in victim_list:
    # Proceed as above
</code></pre>

<p>Are you familiar with the Python construct <em>generator</em>?  It's like a function that returns its value with a <strong>yield</strong>, not a <strong>return</strong>.  If so, use that instead of the above list.</p>

python python-3.x