Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?

Original: food_amounts = [{"sugar_grams":245,"carbohydrate":83,"fiber":67},{"carbohydrate":74,"sugar_grams":52,"fiber":26},{"fiber":47,"carbohydrate":93,"sugar_grams":6}]

/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/bin/python3.6 /Users/edward_chiang/python_projects/sort/sort.py
food_amounts by sugar_grams: [{'sugar_grams': 245, 'carbohydrate': 83, 'fiber': 67}, {'carbohydrate': 74, 'sugar_grams': 52, 'fiber': 26}, {'fiber': 47, 'carbohydrate': 93, 'sugar_grams': 6}]
food_amounts by carbohydrate: [{'fiber': 47, 'carbohydrate': 93, 'sugar_grams': 6}, {'sugar_grams': 245, 'carbohydrate': 83, 'fiber': 67}, {'carbohydrate': 74, 'sugar_grams': 52, 'fiber': 26}]
food_amounts by fiber: [{'sugar_grams': 245, 'carbohydrate': 83, 'fiber': 67}, {'fiber': 47, 'carbohydrate': 93, 'sugar_grams': 6}, {'carbohydrate': 74, 'sugar_grams': 52, 'fiber': 26}]

Process finished with exit code 0
import operator
food_amounts = [{"sugar_grams":245,"carbohydrate":83,"fiber":67},{"carbohydrate":74,"sugar_grams":52,"fiber":26},{"fiber":47,"carbohydrate":93,"sugar_grams":6}]
sugar_gram_list = sorted(food_amounts, key=operator.itemgetter("sugar_grams"), reverse=True)
print('food_amounts by sugar_grams: ' + str(sugar_gram_list))
carbohydrate_list = sorted(food_amounts, key=operator.itemgetter("carbohydrate"), reverse=True)
print('food_amounts by carbohydrate: ' + str(carbohydrate_list))
fiber_list = sorted(food_amounts, key=operator.itemgetter("fiber"), reverse=True)
print('food_amounts by fiber: ' + str(fiber_list))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.