Python程序以最大数量的键提取字典
给定一个字典列表,任务是编写一个Python程序来提取具有最大键数的字典。
Input : test_list = [{‘Gfg’ : 1}, {‘Gfg’ : 1, ‘is’ : 5, ‘best’ : 4}, {‘Gfg’ : 2, ‘best’ : 9}]
Output : {‘Gfg’ : 1, ‘is’ : 5, ‘best’ : 4}
Explanation : Dictionary with max. length 3 is output.
Input : test_list = [{‘Gfg’ : 1}, {‘Gfg’ : 2, ‘best’ : 9}]
Output : {‘Gfg’ : 2, ‘best’ : 9}
Explanation : Dictionary with max. length 2 is output.
方法 1:使用len()和循环
在这里,我们迭代所有字典并跟踪其键的数量,在每一步比较和更新最大值。
此方法仅显示找到的具有最大元素数的第一个字典,即,如果多个字典具有相同的元素数并且该数字最大,则将仅显示第一个字典。
例子:
Python3
# initializing list
test_list = [{'Gfg': 1}, {'Gfg': 1, 'is': 5, 'best': 4}, {'Gfg': 2, 'best': 9}]
# printing original list
print("The original list is : " + str(test_list))
res = dict()
max_len = 0
for sub in test_list:
# comparing and updating maximum dictionary acc. to length
if len(sub) > max_len:
res = sub
max_len = len(sub)
# printing result
print("Dictionary with maximum keys : " + str(res))
Python3
# initializing list
test_list = [{'Gfg': 1}, {'Gfg': 1, 'is': 5, 'best': 4},
{'Gfg': 2, 'best': 9, "book": 1}]
# printing original list
print("The original list is : " + str(test_list))
max_len = max(len(sub) for sub in test_list)
res = [sub for sub in test_list if len(sub) == max_len]
# printing result
print("Dictionary with maximum keys : " + str(res))
输出:
The original list is : [{‘Gfg’: 1}, {‘Gfg’: 1, ‘is’: 5, ‘best’: 4}, {‘Gfg’: 2, ‘best’: 9}]
Dictionary with maximum keys : {‘Gfg’: 1, ‘is’: 5, ‘best’: 4}
方法 2:使用max()和列表推导式
在这里,我们得到字典列表中存在的键数的最大长度。然后提取计算出的最大长度的字典。此方法允许匹配键的多个结果。
例子:
蟒蛇3
# initializing list
test_list = [{'Gfg': 1}, {'Gfg': 1, 'is': 5, 'best': 4},
{'Gfg': 2, 'best': 9, "book": 1}]
# printing original list
print("The original list is : " + str(test_list))
max_len = max(len(sub) for sub in test_list)
res = [sub for sub in test_list if len(sub) == max_len]
# printing result
print("Dictionary with maximum keys : " + str(res))
输出:
The original list is : [{‘Gfg’: 1}, {‘Gfg’: 1, ‘is’: 5, ‘best’: 4}, {‘Gfg’: 2, ‘best’: 9, ‘book’: 1}]
Dictionary with maximum keys : [{‘Gfg’: 1, ‘is’: 5, ‘best’: 4}, {‘Gfg’: 2, ‘best’: 9, ‘book’: 1}]