Iterate over a dictionary
We can use the for
loop to iterate over all the keys in a dictionary:
d = {'apple':'red', 'pear':'green', 'banana':'yellow', 'plum':'purple'}
for k in d:
print(k, ' is ', d[k])
Console result (the order may be different):
apple is red
pear is green
banana is yellow
plum is purple
Here in the for
loop, variable k
receives the keys of dictionary d
('apple', 'pear', ...
). Then d[k]
is used to access the value paired with the key k
('red', 'green', ...
).
Demo Dictionaries in CodeCraft
We can use a dictionary to store column colors and height values to build columns. .
Example:
collection = {'box_red':10, 'box_green': 6, 'box_blue': 8, 'box_pink':2}
x = 0
for m in collection:
print(m)
column(x, -20, collection[m], m)
x += 2
See console result:
box_red
box_green
box_blue
box_pink