0
1

More than 3 years have passed since last update.

collections.ChainMap

Posted at
import collections


a = {'a': 'a', 'c': 'c', 'num': 0}
b = {'b': 'b', 'c': 'cc'}
c = {'b': 'bbb', 'c': 'ccc'}


# class DeepChainMap(collections.ChainMap):
#     def __setitem__(self, key, value):
#         for mapping in self.maps:
#             if key in mapping:
#                 if type(mapping[key]) is int and mapping[key] < value:
#                     mapping[key] = value
#                 return
#         self.maps[0][key] = value
#
#
# m = DeepChainMap(a, b, c)
# m['new_num'] = 1
# print(m['num'])
# print(m['new_num'])

# print(a)
# a.update(b)
# print(a)
# a.update(c)
# print(a)


m = collections.ChainMap(a, b, c)
print(m)
print(m.maps)
m.maps.reverse()
print(m.maps)
m.maps.insert(0, {'c': 'CCCCCC'})
print(m.maps)
del m.maps[0]
print(m.maps)
print(m['c'])
m['b'] = 'BBBBBBB'
print(m.maps)

実行結果;

ChainMap({'a': 'a', 'c': 'c', 'num': 0}, {'b': 'b', 'c': 'cc'}, {'b': 'bbb', 'c': 'ccc'})
[{'a': 'a', 'c': 'c', 'num': 0}, {'b': 'b', 'c': 'cc'}, {'b': 'bbb', 'c': 'ccc'}]
[{'b': 'bbb', 'c': 'ccc'}, {'b': 'b', 'c': 'cc'}, {'a': 'a', 'c': 'c', 'num': 0}]
[{'c': 'CCCCCC'}, {'b': 'bbb', 'c': 'ccc'}, {'b': 'b', 'c': 'cc'}, {'a': 'a', 'c': 'c', 'num': 0}]
[{'b': 'bbb', 'c': 'ccc'}, {'b': 'b', 'c': 'cc'}, {'a': 'a', 'c': 'c', 'num': 0}]
ccc
[{'b': 'BBBBBBB', 'c': 'ccc'}, {'b': 'b', 'c': 'cc'}, {'a': 'a', 'c': 'c', 'num': 0}]
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1