Dictionaries

defaultdict()

defaultdict(list) example:

Using list as the default_factory, it is easy to group a sequence of key-value pairs into a dictionary of lists:

New keys are added automatically.

Note that when a key is repeated (e.g., blue), the item it’s paired with is added to the list.

>>> s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
>>> d = defaultdict(list)
>>> for k, v in s:
        d[k].append(v)

>>> sorted(d.items())
[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]

dict comprehension

Dict from a list of tuples

Given: Each letter of the alphabet occurs only once within scrabble_scores

Goal: Create a dict whose keys are the letters (A - Z) and values are the scores for each letter.

>>> scrabble_scores = [(1, "E A O I N R T L S U"), (2, "D G"), (3, "B C M P"),
                       (4, "F H V W Y"), (5, "K"), (8, "J X"), (10, "Q Z")]

>>> LETTER_SCORES = {letter: score for score, letters in scrabble_scores
                     for letter in letters.split()}
>>> LETTER_SCORES
{'A': 1, 'C': 3, 'B': 3, 'E': 1, 'D': 2, 'G': 2, 'F': 4, 'I': 1, 'H': 4, 'K': 5,
 'J': 8, 'M': 3, 'L': 1, 'O': 1, 'N': 1, 'Q': 10, 'P': 3, 'S': 1, 'R': 1, 'U': 1,
 'T': 1, 'W': 4, 'V': 4, 'Y': 4, 'X': 8, 'Z': 10}
>>>

Sorting List Dict Values

Return this dict with the models for each brand sorted.

cars = {
    'Ford': ['Falcon', 'Focus', 'Festiva', 'Fairlane'],
    'Holden': ['Commodore', 'Captiva', 'Barina', 'Trailblazer'],
    'Nissan': ['Maxima', 'Pulsar', '350Z', 'Navara'],
    'Honda': ['Civic', 'Accord', 'Odyssey', 'Jazz'],
    'Jeep': ['Grand Cherokee', 'Cherokee', 'Trailhawk', 'Trackhawk']
}



return {manufacturer: sorted(models) for
            manufacturer, models in cars.items()}

Dict from keywords

Example:

>>> games_won = dict(sara=0, bob=1, tim=5, julian=3, jim=1)
>>> games_won
{'julian': 3, 'bob': 1, 'jim': 1, 'sara': 0, 'tim': 5}
>>>

dict.get(key)

dict.get(key) defaults to ‘None’, or can choose, so if key not found it doesn’t raise KeyError.

>>> my_dict = {'First':'Tony'}
>>> my_dict['First']
'Tony'
>>> my_dict['Last']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'Last'

>>> my_dict.get('Last')
>>>

dict.items()

dict.items() produces a list of tuples, each containing a key - value pair from the dictionary.

Example:

>>> games_won
{'julian': 3, 'bob': 1, 'jim': 1, 'sara': 0, 'tim': 5}

>>> games_won.items()
[('julian', 3), ('bob', 1), ('jim', 1), ('sara', 0), ('tim', 5)]
>>>

dict.values()

The dict.values() method returns an iterable of type dict_values containing the values in a dictionary’s key value pair. Example:

>>> ninja_belts.values()
dict_values([BeltStats(score=50, ninjas=11),
             BeltStats(score=100, ninjas=7),
             BeltStats(score=175, ninjas=1),
             BeltStats(score=250, ninjas=5)])