Entry
How do you get values from a dictionary and store them in a variable?
Oct 28th, 2001 08:43
Steve Holden, Ken Miner,
Individual values are accessed from a dictionary using subscripts, the
same way that they are added. For example:
dct = {}
creates a dictionary.
dct["greeting"] = "hello"
dct["close"] = "sincerely"
stores the value "hello" in the dictionary under the key "greeting",
and the value "sincerely" under the key "close".
g = dct["greeting"]
stores the value "hello", retrieved from the dictionary using the
key "greeting", in the variable g.
Dictionaries have a values() method that returns a list of the values
in the dictionary. After running the code above, the statement
v = dct.values()
would bind the list of values to the variable v, so
print v
would print
['hello', 'sincerely']
You can iterate over the values using standard iterative forms such as
for vv in v:
print vv
In the general case you cannot predict the order in which the values
will appear in the list, because it depends on the mechanics of
dictionary implementation which are not specified, and might change
from version to version.