Iterate over a dictionary
Iterate over a dictionary means iterate over the keys in the dictionary, we can use for loop
to iterate over the keys in a dictionary.
d = {'apple':'red', 'pear':'green', 'banana':'yellow', 'plum':'purple'}
for k in d:
print(k, 'is ', d[k])
run...
apple is red
pear is green
banana is yellow
plum is purple # (the order may be different)
here in the for
loop, k
means the keys of dictionary d
('apple', 'pear'
...); while d[k]
means the value paired with the key k
(they are 'red', 'green'
...)
===
Use dictionary in CodeCraft
Use dictionary to store (x,y) coordinates in CodeCraft
xh = {1:3, 2:6, 3:9} # x:h pairs
for k in xh:
column(key, -20, xh[k], 2)
The above app will build some cobblestone columns at x: 1,2,3
with corresponding height h: 3,6,9
.
For your understanding:
Exercise 1
Continue with the above app, see if you understand the following code:
for k in xh:
for i in range(key):
block(i, xh[k], -20, 1)
Did you get the same horizontal brick lines with length of 1,2,3 at vertical locations 3,6,9? See the picture.
Exercise 2
If you call on function column()
instead of block()
in the same nesting loops, what do you expect? Guess before check out the following code and picture.
for k in xh:
for i in range(k):
column(i, (-20-i), xh[k], 1)
We vary the z value a little so all the structures will show up at different z layers. See in pic??, we get 3 sheets of blocks, width x, height y.
===end here?