Dictionary comprehension not maintaining key order
I want to use a dictionary comprehension to select key:value pairs from a dictionary into a new dictionary, but the keys are not maintaining the order in which I select them:
# --- Using Python 3.13.2 ---
groceries = {"apple": "red", "kiwi": "green", "banana": "yellow", "grapes": "purple"}
fields_to_select = ["banana", "kiwi", "apple"]
# Create a new dict with the selected fields
{k: groceries[k] for k in groceries.keys() & fields_to_select}
# result has the keys not in the selected order:
# {'apple': 'red', 'kiwi': 'green', 'banana': 'yellow'}
#
# what I want is the keys in the order I "selected" them ("banana", "kiwi", "apple")
# {'banana': 'yellow', 'kiwi': 'green', 'apple': 'red'}