Dictionaries contain key-value pairs. Keys are like a list's indexes. Dictionaries are mutable. Variables hold references to dictionary values, not the dictionary value itself.
myCat = {'size': 'fat', 'color': 'gray', 'disposition': 'loud'}
myCat['size']
'My cat has ' + myCat['color'] + ' fur.'
Unlike list, Dictionaries are unordered. There is no "first" key-value pair in a dictionary.
spam = {12345: 'Luggage combination', 42: 'The Answer'}
[1, 2, 3] == [3, 2, 1]
eggs = {'name': 'Zophie', 'species': 'cat'}
ham = {'species': 'cat', 'name': 'Zophie'}
eggs == ham
eggs = {'name': 'Zophie', 'species': 'cat'}
# eggs('color') # KeyError
'name' in eggs
'name' not in eggs
eggs = {'name': 'Zophie', 'species': 'cat'}
eggs.keys()
list(eggs.keys())
The values()
method will return list-like values of a dicitonary's values
eggs = {'name': 'Zophie', 'species': 'cat'}
list(eggs.values())
The items()
method will return list-like values of a dicitonary's keys and values
eggs = {'name': 'Zophie', 'species': 'cat'}
list(eggs.items())
for k in eggs.keys():
print(k)
for v in eggs.values():
print(v)
for k, v in eggs.items():
print(k, v)
The below expression returns a tuple. Tuple: similar to list but immutable and use ()
for i in eggs.items():
print(i)
'cat' in eggs.values()
The get()
method can return a default value if a key doesn't exist. It can be used to prevent KeyError
eggs.get('name', 0)
No key named "age" in object "eggs", return 0
eggs.get('age', 0)
The setdefault()
dictionary method can set a value if a key doesn't exist.
eggs.setdefault('color', 'black')
eggs
eggs.setdefault('color', 'orange')
eggs
message = "It was a bright cold day in April, and the clocks were striking thirteen"
count = {}
for character in message.upper():
count.setdefault(character, 0)
count[character] = count[character] + 1
print(count)
Use triple ticks to enclose a large block of text and to paste multi-line text (more on chapter 19) e.g. copy and paste the entire text of Shakespeare's 'Romeo & Juliet' in the program by adding '''
after "message = " and at the end of copied text in the program
The pprint
module's pprint()
"pretty print" function can display a dictionary value cleanly and orderly.
import pprint
''' Same program here
Replace print(count) with '''
pprint.pprint(count)
The pformat()
function returns a string value of this output.
import pprint
''' Same program here
Replace print(count) with '''
rjtext = pprint.pformat(count)
print(rjtext)
cat = {'name': 'Zophie', 'age': 7, 'color': 'gray'}
allCats = [] # Blank list
allCats.append({'name': 'Zophie', 'age': 7, 'color': 'gray'})
allCats.append({'name': 'Pooka', 'age': 5, 'color': 'black'})
allCats.append({'name': 'Fat-tail', 'age': 5, 'color': 'gray'})
The slots of a tic-tac-toe board with their corresponding keys
theBoard = {
'top-L':' ', 'top-M':' ', 'top-R':' ',
'mid-L':' ', 'mid-M':' ', 'mid-R':' ',
'low-L':' ', 'low-M':' ', 'low-R':' '
}
import pprint
pprint.pprint(theBoard)
theBoard['mid-M'] = 'X'
The first move
theBoard['top-L'] = 'O'
theBoard['top-M'] = 'O'
theBoard['top-R'] = 'O'
theBoard['mid-L'] = 'X'
theBoard['low-R'] = 'X'
Player O wins
Convert dictionary to output
def printBoard(board):
print(board['top-L'] + '|' + board['top-M'] + '|' + board['top-R'])
print('-----')
print(board['mid-L'] + '|' + board['mid-M'] + '|' + board['mid-R'])
print('-----')
print(board['low-L'] + '|' + board['low-M'] + '|' + board['low-R'])
type(42)
type('42')
type(3.14)
type(theBoard)
type(theBoard['top-R'])