Python Forum

Full Version: looking for a multi item container
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
this would be quite easy to implement; perhaps easier than the effort to find an existing one (since i am not very good at the latter), perhaps already in Python under some name not obvious to me. what i need soon is a mapping which lets me insert duplicate entries under the same key and maintains order of insertion within the same key. it also needs to be able to provide items in that order after a search for that key as opposed just doing so via an iteration from the beginning. IoW, it needs to be able to move the current position forward or backward based on a given key being searched.
If i understand the requirements correctly, you could use a defaultdict with its values in a deque
import collections

container = collections.defaultdict(collections.deque)

container['one'].append(1)
container['one'].append(1)
container['one'].append(2)
container['one'].append(3)
container['one'].append(2)

print(container['one'])

container['one'].rotate(1)

print(container['one'])

container['one'].rotate(-2)

print(container['one'])
Output:
deque([1, 1, 2, 3, 2]) deque([2, 1, 1, 2, 3]) deque([1, 2, 3, 2, 1])
i was going to implement my own with a dict and each item being a list. it would all be inside something where i can keep a current key and index. i implemented this in C ages ago as a binary tree and it made lots of things so much easier. sometimes i wonder what life would be like if i went back to C. would i implement pythonic-like things such as generators and iterators?