Python-dictionary
dictionary and import
1 | spam={'name':'Zophie','age':7} |
values
&keys
&items
1 | spam={'color':'red','age':'42'} |
out:
red
42
color
age
(‘color’, ‘red’)
(‘age’, ‘42’)
use the factor in dictionary to form list
1 | spam={'color':'red','age':'42'} |
use the factors in items
at the same time
1 | spam={'color':'red','age':'42'} |
out:
Key: color Value: red
Key: age Value: 42
use the keys
to find the values
1 | numbers={'one':1,'two':2,'three':3} |
but values
can’t be used to find keys
1 | numbers={"one": 1, "two": 2} |
1 | --------------------------------------------------------------------------- |
use with sort
1 | numbers={"one": 1, "two": [4, 6, 3], "three": 3} |
out:
[4, 6, 3]
[3, 4, 6]
use pop
to delete items
1 | numbers={1: 2, 3:4} |
use get
to get values
1 | d={"uno":["one",1],"dos":["two",2]} |
if there is no key
1 | d={"uno":["one",1],"dos":["two",2]} |
example for dictionary
1 | k=input() |
out:
Jim | Jim |
---|---|
78 | 90 |
76 | 78 |
90 | 80 |
not pass | (‘Jim’, (90, 78, 80)) |
use setdefault
to add items to dictionary
1 | spam={'name':'Pooka','age':5} |
out: {‘name’: ‘Pooka’, ‘age’: 5, ‘color’: ‘black’}
1 | message='It was a bright cold day in April,and the clocks were striking thirtheen.' |
out: {‘I’: 1, ‘t’: 6, ‘ ‘: 12, ‘w’: 2, ‘a’: 4, ‘s’: 3, ‘b’: 1, ‘r’: 5, ‘i’: 6, ‘g’: 2, ‘h’: 4, ‘c’: 3, ‘o’: 2, ‘l’: 3, ‘d’: 3, ‘y’: 1, ‘n’: 4, ‘A’: 1, ‘p’: 1, ‘,’: 1, ‘e’: 5, ‘k’: 2, ‘.’: 1}
use of pprint
1 | import pprint |
out:{‘A’: 9, ‘A*’: 2}
used in game:
create background
1 | theBoard = {'top-L': ' ', 'top-M': ' ', 'top-R': ' ', |
| |
-+-+-
| |
-+-+-
| |
1 | theBoard = {'top-L': 'O', 'top-M': 'O', 'top-R': 'O', 'mid-L': 'X', 'mid-M': |
O|O|O
-+-+-
X|X|
-+-+-
| |X
1 | turn = 'X' |
O|O|O
-+-+-
X|X|
-+-+-
| |X
Turn for X. Move on which space?
top-L
X|O|O
-+-+-
X|X|
-+-+-
| |X
… …
another example to record the number:
1 | allGuests={'Alice':{'apples':5,'pretzels':12}, |
Number of things being brought:
- Apples 7
- Cups 3
- Cakes 0
- Ham Sandwiches 3
- Apple Pies 1