top | item 14298121

(no title)

bathyspheric | 8 years ago

It thought ChainMap might be useful (Python) but found out I need to be a lot more careful using it.

    from collections import ChainMap

    a, b, c = {'a': 1}, {'b': 12, 'c': 13}, {'c': 23}
    d = ChainMap(a, b, c) # ChainMap({'a': 1}, {'b': 12, 'c': 13}, {'c': 23})
    e = ChainMap(c, b, a) # ChainMap({'c': 23}, {'b': 12, 'c': 13}, {'a': 1})

    # Lookups cascade
    d['c']  # -> 13
    e['c']  # -> 23

    # Updates mutate first dict
    d['c'] = 1003 # ChainMap({'a': 1, 'c': 1003}, {'b': 12, 'c': 13}, {'c': 23})
 
    d['c'] # 1003
    e['c'] # 23
    a   # {'a': 1, 'c': 1003}
Python 3.3+ https://docs.python.org/3/library/collections.html#collectio...

discuss

order

sametmax|8 years ago

You can add an empty dictionary as the first argument if you want to prevent that.