📜  Python – 具有最大对数的字典

📅  最后修改于: 2022-05-13 01:54:41.837000             🧑  作者: Mango

Python – 具有最大对数的字典

给定字典列表,提取具有最大键的字典。

方法 #1:使用 len() + 循环

在此,我们对每个字典进行迭代并比较每个字典的长度,记录并返回具有最大长度的一个。

Python3
# Python3 code to demonstrate working of 
# Dictionary with maximum keys
# Using loop + len()
  
# initializing list
test_list = [{"gfg": 2, "best" : 4}, 
             {"gfg": 2, "is" : 3, "best" : 4}, 
             {"gfg": 2}]
  
# printing original list
print("The original list is : " + str(test_list))
  
res = {} 
max_len = 0
for ele in test_list:
      
    # checking for lengths
    if len(ele) > max_len: 
        res = ele
        max_len = len(ele)
          
# printing results
print("Maximum keys Dictionary : " + str(res))


Python3
# Python3 code to demonstrate working of 
# Dictionary with maximum keys
# Using max() + key = len
  
# initializing list
test_list = [{"gfg": 2, "best" : 4}, 
             {"gfg": 2, "is" : 3, "best" : 4}, 
             {"gfg": 2}]
  
# printing original list
print("The original list is : " + str(test_list))
  
# maximum length dict using len param
res = max(test_list, key = len)
          
# printing results
print("Maximum keys Dictionary : " + str(res))


输出
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}

方法 #2:使用 max() + key=len

在此,我们使用 max() 计算最大长度密钥,方法是传递附加密钥“len”以根据长度进行比较。

Python3

# Python3 code to demonstrate working of 
# Dictionary with maximum keys
# Using max() + key = len
  
# initializing list
test_list = [{"gfg": 2, "best" : 4}, 
             {"gfg": 2, "is" : 3, "best" : 4}, 
             {"gfg": 2}]
  
# printing original list
print("The original list is : " + str(test_list))
  
# maximum length dict using len param
res = max(test_list, key = len)
          
# printing results
print("Maximum keys Dictionary : " + str(res))
输出
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}