Python Introduction | Lists, Tuples, Ranges, Sets, and Dictionaries | Managing Values with Dictionaries
Lists and tuples manage values by numeric index. Python dictionaries manage values by key instead.
Create a dictionary with braces or with dict.
variable = {key1: value1, key2: value2, ...}
variable = dict(key1=value1, key2=value2, ...)
Use brackets to retrieve or assign a value.
variable = dictionary[key]
dictionary[key] = value
A dictionary uses keys, not numeric positions. It is not a sequence.
Using for in
Iterating over a dictionary returns its keys. Use each key to retrieve its value.
dic = {'taro':'taro@yamada.com',
'hanako':'hanako@flower',
'ichiro':'ichiro@baseball'}
for n in dic:
print(n + ' (' + dic[n] + ')')
This example uses names as keys and email addresses as values. Dictionaries are useful for small database-like collections.
Dictionary Operations
Adding or Updating a Value
dictionary[key] = value
If the key does not exist, Python adds a new entry. If it exists, Python updates the value.
Deleting a Value
del dictionary[key]
Obtaining All Keys
variable = dictionary.keys()
Obtaining All Values
variable = dictionary.values()
Obtaining All Items
variable = dictionary.items()
items() returns key-value pairs. Choose dictionaries when named keys are more useful than numeric positions.