Dictionaries & sets
Key–value maps, uniqueness, counting, grouping, and fast lookups.
How to Convert a Counter to a Plain Dict with Sorted Items in Python
This code converts a collections.Counter into a regular dictionary with items sorted by key, useful for stable, readable output.
from collections import Counter
def counter_to_sorted_dict(counter):
"""Convert a Counter to a plain dict with sorted items."""
return dict(sorted(counter.items()))
if __name__ == "__main__":
# Example usage
data = Counter(['apple', 'banana', 'apple', 'cherry', 'banana', 'date', 'apple'])
print("…
How to Sort Dictionary Keys Alphabetically in Python
This code returns a list of dictionary keys sorted alphabetically, using a case-insensitive comparison while preserving the original insertion order for keys that are equal.
data = {
"banana": 3,
"apple": 1,
"Cherry": 5,
"date": 2,
"apple": 4,
"Fig": 6,
"banana": 2,
}
def sort_dict_keys_alphabetically(d):
"""Return a list of keys sorted alphabetically (case-insensitive), stable for duplicates."""
return sorted(d.keys(), key=lambda k: k.lower())
if __n…
How to Sort a List of Dictionaries by Key in Python
Sort a list of dictionaries by various keys (grade, age, name) using lambda, itemgetter, and extract unique sorted names into a set.
from operator import itemgetter
# Sample data: a list of dictionaries representing students
students = [
{"name": "Alice", "grade": 88, "age": 23},
{"name": "Bob", "grade": 95, "age": 22},
{"name": "Charlie", "grade": 78, "age": 24},
{"name": "Diana", "grade": 92, "age": 21}
]
# Sort by grade (descen…
How to Sort a Python Dictionary by Value Descending
Sort dictionary items by their values in descending order and return a new dictionary.
def sort_dict_by_value_desc(d):
return dict(sorted(d.items(), key=lambda item: item[1], reverse=True))
if __name__ == "__main__":
sample = {"apple": 5, "banana": 2, "cherry": 8, "date": 8}
result = sort_dict_by_value_desc(sample)
print(result)
Browse by section
Each section groups closely related Python snippets.
Dictionaries & sets — Python code examples
What you will find here
This page collects dictionaries & sets snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.
Samples vs tutorials and challenges
Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.