Python program to get maximum of each key Dictionary List

PythonServer Side ProgrammingProgramming

<p>When it is required to get the maximum of each key in a list of dictionary elements, a simple iteration is used.</p><h2>Example</h2><p>Below is a demonstration of the same</p><pre class="demo-code notranslate language-python" data-lang="python">my_list = [{&quot;Hi&quot;: 18, &quot;there&quot;: 13, &quot;Will&quot;: 89}, {&quot;Hi&quot;: 53, &quot;there&quot;: 190, &quot;Will&quot;: 87}] print(&quot;The list is : &quot;) print(my_list) my_result = {} for elem in my_list: for key, val in elem.items(): if key in my_result: my_result[key] = max(my_result[key], val) else: my_result[key] = val print(&quot;The result is : &quot;) print(my_result)</pre><h2>Output</h2><pre class="result notranslate">The list is : [{&#39;Will&#39;: 89, &#39;there&#39;: 13, &#39;Hi&#39;: 18}, {&#39;Will&#39;: 87, &#39;there&#39;: 190, &#39;Hi&#39;: 53}] The result is : {&#39;Will&#39;: 89, &#39;there&#39;: 190, &#39;Hi&#39;: 53}</pre><h2>Explanation</h2><ul class="list"><li><p>A list of dictionary is defined and is displayed on the console.</p></li><li><p>An empty dictionary is defined.</p></li><li><p>The list is iterated over, and the elements are accessed.</p></li><li><p>If the key is present in the previously defined dictionary, the maximum of the key and the value is determined, and stored in the &lsquo;key&rsquo; index of the dictionary.</p></li><li><p>Otherwise, the value is stored in the &lsquo;key&rsquo; index of the dictionary.</p></li><li><p>This is displayed as the output on the console.</p></li></ul>
raja
Updated on 16-Sep-2021 08:35:40

Advertisements