I would like to itterate through a list of dictionaries and check every Quantity key and compare the values and then print/display the Dictionary with the highest quantity value.
For example. This is my list of dictionaries. I have multiple keys and values and I want to compare the Quantity Values of each Dictionary. I then want to display only the Dictionary that has the highest value.
List_of_dict = [{'Country': 'China', 'Code': BHK234, 'Product': 'Nike Air','Price': '1245', 'Quantity': '12'}, {'Country': 'South Africa', 'Code': BAK274, 'Product': 'Nike Air 1','Price': '1945', 'Quantity': '34'}]
CodePudding user response:
you can use this example with your code
list_of_dict.sort(key=lambda x: x['Quantity'], reverse=True)
max_dicts = [d for d in list_of_dict if d['Quantity'] == list_of_dict[0]['Quantity']]
CodePudding user response:
products = [{'Country': 'China', 'Code': 'BHK234', 'Product': 'Nike Air','Price': '1245', 'Quantity': '12'}, {'Country': 'South Africa', 'Code': 'BAK274', 'Product': 'Nike Air 1','Price': '1945', 'Quantity': '34'}]
quantities = [i["Quantity"] for i in products]
print(products[quantities.index(max(quantities))])
To get the the highest quantity value from a list of dictionaries, you can just iterate through the list, collect the quantities, get the index of the highest value and use that to get the dictionary.
CodePudding user response:
You can use python built-in function max()
with a custom function that will provide a custom key for item comparison in your list:
list_of_dicts = [{'Country': 'China', 'Code': 'BHK234', 'Product': 'Nike Air','Price': '1245', 'Quantity': '12'}, {'Country': 'South Africa', 'Code': 'BAK274', 'Product': 'Nike Air 1','Price': '1945', 'Quantity': '34'}]
print(max(list_of_dicts, key=lambda x: x['Quantity']))
will ouput
{'Country': 'South Africa', 'Code': 'BAK274', 'Product': 'Nike Air 1', 'Price': '1945', 'Quantity': '34'}