VOOZH about

URL: https://www.geeksforgeeks.org/python/python-dictionary-with-maximum-count-of-pairs/

⇱ Python - Dictionary with maximum count of pairs - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Python - Dictionary with maximum count of pairs

Last Updated : 2 Sep, 2020

Given dictionary list, extract dictionary with maximum keys.

Input : test_list = [{"gfg": 2, "best" : 4}, {"gfg": 2, "is" : 3, "best" : 4, "CS" : 9}, {"gfg": 2}] Output : 4 Explanation : 2nd dictionary has maximum keys, 4. Input : test_list = [{"gfg": 2, "best" : 4}, {"gfg": 2}] Output : 2 Explanation : 1st dictionary has maximum keys, 2.

Method #1 : Using len() + loop

In this, we iterate for each of dictionary and compare lengths of each, record and return one with maximum length.


Output
The original list is : [{'gfg': 2, 'best': 4}, {'gfg': 2, 'is': 3, 'best': 4}, {'gfg': 2}]
Maximum keys Dictionary : {'gfg': 2, 'is': 3, 'best': 4}

Method #2 : Using max() + key=len

In this, we compute maximum length key using max() by passing additional key "len" for comparison based on lengths.


Output
The original list is : [{'gfg': 2, 'best': 4}, {'gfg': 2, 'is': 3, 'best': 4}, {'gfg': 2}]
Maximum keys Dictionary : {'gfg': 2, 'is': 3, 'best': 4}
Comment