Find out what each of the expressions does to the dictionary in the center.
Dictionaries are an unordered, associative array. They have a set of key/value pairs. They are very versatile data structures, but slower than lists. Dictionaries can be used easily as a hashtable.
prices = {
'banana':0.75,
'apple':0.55,
'orange':0.80
}
By applying square brackets with a key inside, the values of a dictionary can be requested. Valid types for keys are strings, integers, floats, and tuples.
print prices['banana'] # 0.75
print prices['kiwi'] # KeyError!
You can access the keys of a dictionary in a for
loop. However, their order is not guaranteed, then.
for fruit in prices:
print fruit
There is a number of functions that can be used on every dictionary:
prices.has_key('apple')
prices.get('banana')
prices.get('kiwi')
prices.setdefault('kiwi', 0.99)
prices.setdefault('banana', 0.99)
# for 'banana', nothing happens
print prices.keys()
print prices.values()
print prices.items()
What do the following commands produce?
d = {1:'A', 'B':1, 'A':True}
print(d['A'])
-
False
-
"B"
-
True
-
1
What do these commands produce?
d = {1:'A', 'B':1, 'A':True}
print(d.has_key('B'))
-
1
-
True
-
"B"
-
False
What do these commands produce?
d = {1:'A', 'B':1, 'A':True}
print(d.values())
-
True
-
['A', 1, True]
-
3
-
[1, 'B', 'A']
What do these commands produce?
d = {1:'A', 'B':1, 'A':True}
print(d.keys())
-
[1, 'B', 'A']
-
['A', 'B', 1]
-
[1, 'A', 'B']
-
The order may vary
What do these commands produce?
d = {1:'A', 'B':1, 'A':True}
print(d['C'])
-
None
-
'C'
-
an Error
-
False
What do these commands produce?
d = {1:'A', 'B':1, 'A':True}
d.setdefault('C', 3)
print(d['C'])
-
3
-
'C'
-
None
-
an Error