Mapping Types

There is currently only one standard mapping type in Python, the dictionary. Operations and methods of the dict type in RPython are similar with Python.

def rdict():
    def print_dict(d):
        for k, v in d.iteritems(): print k, v

    d = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5}
    print_dict(d)

    print "len: ", len(d)
    print "d[key]: ", d['one']

    d['one'] = 3
    print "d[key] = value: ", d['one']

    del d['one']
    try:
        print "d[key] = value: ", d['one']
    except KeyError:
        print "KeyError: not found."

    if 'one' not in d:
        print "'one' is not in d"

    # iterator over a dictionary
    for i in iter(d): print i
    for i in d.iterkeys(): print i
    for i in d.itervalues(): print i
    for i in d.keys(): print i
    for i in d.values(): print i

    d.pop('five')
    k, v = d.popitem()
    print k, v

    d.update({'five': 55})

def entry_point(argv):
    rdict()
    return 0

def target(*args): return entry_point
if __name__ == "__main__": import sys; entry_point(sys.argv)

As you can see, most methods of dictionary are supported in RPython. However, there are some exceptions.

Attention

  • dicts with a unique key type only, provided it is hashable

  • custom hash functions and custom equality will not be honored. Use rpython.rlib.objectmodel.r_dict for custom hash functions.

  • the dictionary view object is not supported in RPython.

################### UNSUPPORTED IN RPYTHON ######################

def dict_unsupported():
    d1 = dict(one=1, two=2, three=3)
    d2 = dict({'one': 1, 'two': 2, 'three': 3})
    d3 = dict([('two', 2), ('one', 1), ('three', 3)])
    d4 = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
    print d1
    print d2
    print d3
    print d4

    # There is no dictionary view objects in RPython
    d5 = dict({'three': 3, 'four': 4, 'five': 5})
    v1 = d1.viewkeys()
    v5 = d5.viewkeys()
    print v1 & v5
    print v1 | v5
    print v1 - v5
    print v1 ^ v5

    # keys in different types are note supported in RPython
    d6 = dict({1: 1, 'two': 2})
    print d6[1], d6['two']

def entry_point(argv):
    dict_unsupported()
    return 0

def target(*args): return entry_point
if __name__ == "__main__": import sys; entry_point(sys.argv)