------------------------------------------------------------------------------
MC logo
Dictionary Objects
[^] Code Examples
------------------------------------------------------------------------------
<<Tuples dict.py Sorted User Lister>>
#!/usr/bin/python3

# Dictionaries map keys to values.

fred = { 'mike': 456, 'bill': 399, 'sarah': 521 }

# Subscripts.
try:
    print(fred)
    print(fred['bill'])
    print(fred['nora'])
    print("Won't see this!")
except KeyError as rest:
    print("Lookup failed:", rest)
print()

# Entries can be added, udated, or deleted.
fred['bill'] = 'Sopwith Camel'
fred['wilma'] = 2233
del fred['mike']
print(fred)
print()

# Get all the keys.
print(fred.keys())
for k in fred.keys():
    print(k, "=>", fred[k])
print()

# Test for presence of a key.
for t in [ 'zingo', 'sarah', 'bill', 'wilma' ]:
    print(t,end=' ')
    if t in fred:
        print('=>', fred[t])
    else:
        print('is not present.')


Dictionaries are key-value pairs, known as maps or hashes in other languages. The key may be any immutable type, except a tuple may not be used if it contains a any mutable parts.
<<Tuples Sorted User Lister>>