Dictionary Comprehensions

Like the venerable list, dictionaries are extremely useful data structures in Python, and used extensively. Similar to lists, we can build dictionaries from existing collections.

The blueprint is:

my_dict = { key_expression : value_expression for expression in iterable }

This example should make things clearer:

word = 'letters'
letters_count = { letter: word.count(letter) for letter in word}
print(letters_count)

# outputs:

{'l': 1, 'e': 2, 't': 2, 'r': 1, 's': 1}

Another simple example:

from math import sin, radians

d = {angle: sin(radians(angle)) for angle in (0, 45., 90., 135.)}
print(d)

# outputs:

{0: 0.0, 45.0: 0.7071067811865475, 90.0: 1.0, 135.0: 0.7071067811865476}

Just remember you need to select a key and value from the iterable:

class Player:
    def __init__(self, name, strength, score):
        self.name = name
        self.strength = strength
        self.score = score

scores = [Player('Hayden', 'batsman', 34),   Player('Ponting', 'batsman', 26),
          Player('Gilchrist', 'wickie', 53), Player('Warne', 'bowler', 2)] 

batsmen_scores = {p.name: p.score for p in scores if p.strength == 'batsman'}
print(batsmen_scores)

# outputs:

{'Hayden': 34, 'Ponting': 26}

Depending upon how you choose to iterate, generating a dictionary from another dictionary can take this form:

my_dict = {
    my_key: my_value
    for k in other_dict.keys()
}
# iterating by keys

mcase = {'a': 10, 'b': 34, 'A': 7, 'Z': 3}

mcase_freq = {
    k.lower(): mcase.get(k.lower(), 0) + mcase.get(k.upper(), 0)
    for k in mcase.keys()
}

print(mcase_freq)

# outputs:

{'a': 17, 'b': 34, 'z': 3}

Or this form:

my_dict = {
    my_key: my_value
    for k, v in other_dict.items()
}
# iterating by key/value pairs

purchased = {'banana': 2.99, 'bread': 1.50, 'cereal': 4.99}

discounted_purchases = {
    k: v * .80
    for (k, v) in purchased.items()
}

print(discounted_purchases)

# outputs:

{'banana': 2.3920000000000003, 'bread': 1.2000000000000002, 'cereal': 3.9920000000000004}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s