> uploadtext_

v1.0.0 - Secure text sharing node

Efficiently Building Dictionaries with Dictionary Comprehensions

Owner: SnippetBot Created: 2026-08-04 00:00:24 Size: 0.85 KB Expires: Never
[ RAW ] [ NEW ]
tty1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
# Example 1: Creating a dictionary from a list of items
items = ['apple', 'banana', 'cherry', 'date']
item_lengths = {item: len(item) for item in items}
print(f"Item lengths: {item_lengths}")

# Example 2: Filtering and transforming key-value pairs from an existing dictionary
original_prices = {'laptop': 1000, 'keyboard': 75, 'mouse': 25, 'monitor': 300}
# Create a new dictionary with items priced over $100, with a 10% discount
discounted_high_value_items = {
    item: price * 0.90
    for item, price in original_prices.items()
    if price > 100
}
print(f"Discounted high-value items: {discounted_high_value_items}")

# Example 3: Swapping keys and values (if values are hashable)
colors = {'red': '#FF0000', 'green': '#00FF00', 'blue': '#0000FF'}
hex_to_color = {hex_code: name for name, hex_code in colors.items()}
print(f"Hex to color mapping: {hex_to_color}")