collections module

binaryninja.collections.ChainMap(*maps)

A ChainMap groups multiple dicts (or other mappings) together to create a single, updateable view.

binaryninja.collections.Counter([iterable])

Dict subclass for counting hashable items.

binaryninja.collections.OrderedDict

Dictionary that remembers insertion order

binaryninja.collections.UserDict([dict])

binaryninja.collections.UserList([initlist])

A more or less complete user-defined wrapper around list objects.

binaryninja.collections.UserString(seq)

binaryninja.collections.defaultdict

defaultdict(default_factory=None, /, [...]) --> dict with default factory

binaryninja.collections.deque

deque([iterable[, maxlen]]) --> deque object

This module implements specialized container datatypes providing alternatives to Python’s general purpose built-in containers, dict, list, set, and tuple.

  • namedtuple factory function for creating tuple subclasses with named fields

  • deque list-like container with fast appends and pops on either end

  • ChainMap dict-like class for creating a single view of multiple mappings

  • Counter dict subclass for counting hashable objects

  • OrderedDict dict subclass that remembers the order entries were added

  • defaultdict dict subclass that calls a factory function to supply missing values

  • UserDict wrapper around dictionary objects for easier dict subclassing

  • UserList wrapper around list objects for easier list subclassing

  • UserString wrapper around string objects for easier string subclassing

class ChainMap(*maps)

Bases: collections.abc.MutableMapping

A ChainMap groups multiple dicts (or other mappings) together to create a single, updateable view.

The underlying mappings are stored in a list. That list is public and can be accessed or updated using the maps attribute. There is no other state.

Lookups search the underlying mappings successively until a key is found. In contrast, writes, updates, and deletions only operate on the first mapping.

clear()

Clear maps[0], leaving maps[1:] intact.

copy()

New ChainMap or subclass with a new copy of maps[0] and refs to maps[1:]

classmethod fromkeys(iterable, *args)

Create a ChainMap with a single dict created from the iterable.

get(k[, d]) D[k] if k in D, else d.  d defaults to None.
new_child(m=None)

New ChainMap with a new map followed by all previous maps. If no map is provided, an empty dict is used.

pop(key, *args)

Remove key from maps[0] and return its value. Raise KeyError if key not in maps[0].

popitem()

Remove and return an item pair from maps[0]. Raise KeyError is maps[0] is empty.

property parents

New ChainMap from maps[1:].

class Counter(iterable=None, /, **kwds)

Bases: dict

Dict subclass for counting hashable items. Sometimes called a bag or multiset. Elements are stored as dictionary keys and their counts are stored as dictionary values.

>>> c = Counter('abcdeabcdabcaba')  # count elements from a string
>>> c.most_common(3)                # three most common elements
[('a', 5), ('b', 4), ('c', 3)]
>>> sorted(c)                       # list all unique elements
['a', 'b', 'c', 'd', 'e']
>>> ''.join(sorted(c.elements()))   # list elements with repetitions
'aaaaabbbbcccdde'
>>> sum(c.values())                 # total of all counts
15
>>> c['a']                          # count of letter 'a'
5
>>> for elem in 'shazam':           # update counts from an iterable
...     c[elem] += 1                # by adding 1 to each element's count
>>> c['a']                          # now there are seven 'a'
7
>>> del c['b']                      # remove all 'b'
>>> c['b']                          # now there are zero 'b'
0
>>> d = Counter('simsalabim')       # make another counter
>>> c.update(d)                     # add in the second counter
>>> c['a']                          # now there are nine 'a'
9
>>> c.clear()                       # empty the counter
>>> c
Counter()

Note: If a count is set to zero or reduced to zero, it will remain in the counter until the entry is deleted or the counter is cleared:

>>> c = Counter('aaabbc')
>>> c['b'] -= 2                     # reduce the count of 'b' by two
>>> c.most_common()                 # 'b' is still in, but its count is zero
[('a', 3), ('c', 1), ('b', 0)]
copy()

Return a shallow copy.

elements()

Iterator over elements repeating each as many times as its count.

>>> c = Counter('ABCABC')
>>> sorted(c.elements())
['A', 'A', 'B', 'B', 'C', 'C']

# Knuth’s example for prime factors of 1836: 2**2 * 3**3 * 17**1 >>> prime_factors = Counter({2: 2, 3: 3, 17: 1}) >>> product = 1 >>> for factor in prime_factors.elements(): # loop over factors … product *= factor # and multiply them >>> product 1836

Note, if an element’s count has been set to zero or is a negative number, elements() will ignore it.

classmethod fromkeys(iterable, v=None)

Create a new dictionary with keys from iterable and values set to value.

most_common(n=None)

List the n most common elements and their counts from the most common to the least. If n is None, then list all element counts.

>>> Counter('abracadabra').most_common(3)
[('a', 5), ('b', 2), ('r', 2)]
subtract(iterable=None, /, **kwds)

Like dict.update() but subtracts counts instead of replacing them. Counts can be reduced below zero. Both the inputs and outputs are allowed to contain zero and negative counts.

Source can be an iterable, a dictionary, or another Counter instance.

>>> c = Counter('which')
>>> c.subtract('witch')             # subtract elements from another iterable
>>> c.subtract(Counter('watch'))    # subtract elements from another counter
>>> c['h']                          # 2 in which, minus 1 in witch, minus 1 in watch
0
>>> c['w']                          # 1 in which, minus 1 in witch, minus 1 in watch
-1
update(iterable=None, /, **kwds)

Like dict.update() but add counts instead of replacing them.

Source can be an iterable, a dictionary, or another Counter instance.

>>> c = Counter('which')
>>> c.update('witch')           # add elements from another iterable
>>> d = Counter('watch')
>>> c.update(d)                 # add elements from another counter
>>> c['h']                      # four 'h' in which, witch, and watch
4
class OrderedDict

Bases: dict

Dictionary that remembers insertion order

clear() None.  Remove all items from od.
copy() a shallow copy of od
fromkeys(value=None)

Create a new ordered dictionary with keys from iterable and values set to value.

items() a set-like object providing a view on D's items
keys() a set-like object providing a view on D's keys
move_to_end(key, last=True)

Move an existing element to the end (or beginning if last is false).

Raise KeyError if the element does not exist.

pop(k[, d]) v, remove specified key and return the corresponding

value. If key is not found, d is returned if given, otherwise KeyError is raised.

popitem(last=True)

Remove and return a (key, value) pair from the dictionary.

Pairs are returned in LIFO order if last is true or FIFO order if false.

setdefault(key, default=None)

Insert key with a value of default if key is not in the dictionary.

Return the value for key if key is in the dictionary, else default.

update([E, ]**F) None.  Update D from dict/iterable E and F.

If E is present and has a .keys() method, then does: for k in E: D[k] = E[k] If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v In either case, this is followed by: for k in F: D[k] = F[k]

values() an object providing a view on D's values
class UserDict(dict=None, /, **kwargs)

Bases: collections.abc.MutableMapping

copy()
classmethod fromkeys(iterable, value=None)
class UserList(initlist=None)

Bases: collections.abc.MutableSequence

A more or less complete user-defined wrapper around list objects.

append(item)

S.append(value) – append value to the end of the sequence

clear() None -- remove all items from S
copy()
count(value) integer -- return number of occurrences of value
extend(other)

S.extend(iterable) – extend sequence by appending elements from the iterable

index(value[, start[, stop]]) integer -- return first index of value.

Raises ValueError if the value is not present.

Supporting start and stop arguments is optional, but recommended.

insert(i, item)

S.insert(index, value) – insert value before index

pop([index]) item -- remove and return item at index (default last).

Raise IndexError if list is empty or index is out of range.

remove(item)

S.remove(value) – remove first occurrence of value. Raise ValueError if the value is not present.

reverse()

S.reverse() – reverse IN PLACE

sort(*args, **kwds)
class UserString(seq)

Bases: collections.abc.Sequence

capitalize()
casefold()
center(width, *args)
count(value) integer -- return number of occurrences of value
encode(encoding='utf-8', errors='strict')
endswith(suffix, start=0, end=9223372036854775807)
expandtabs(tabsize=8)
find(sub, start=0, end=9223372036854775807)
format(*args, **kwds)
format_map(mapping)
index(value[, start[, stop]]) integer -- return first index of value.

Raises ValueError if the value is not present.

Supporting start and stop arguments is optional, but recommended.

isalnum()
isalpha()
isascii()
isdecimal()
isdigit()
isidentifier()
islower()
isnumeric()
isprintable()
isspace()
istitle()
isupper()
join(seq)
ljust(width, *args)
lower()
lstrip(chars=None)
maketrans()

Return a translation table usable for str.translate().

If there is only one argument, it must be a dictionary mapping Unicode ordinals (integers) or characters to Unicode ordinals, strings or None. Character keys will be then converted to ordinals. If there are two arguments, they must be strings of equal length, and in the resulting dictionary, each character in x will be mapped to the character at the same position in y. If there is a third argument, it must be a string, whose characters will be mapped to None in the result.

partition(sep)
removeprefix(prefix, /)
removesuffix(suffix, /)
replace(old, new, maxsplit=- 1)
rfind(sub, start=0, end=9223372036854775807)
rindex(sub, start=0, end=9223372036854775807)
rjust(width, *args)
rpartition(sep)
rsplit(sep=None, maxsplit=- 1)
rstrip(chars=None)
split(sep=None, maxsplit=- 1)
splitlines(keepends=False)
startswith(prefix, start=0, end=9223372036854775807)
strip(chars=None)
swapcase()
title()
translate(*args)
upper()
zfill(width)
class defaultdict

Bases: dict

defaultdict(default_factory=None, /, […]) –> dict with default factory

The default factory is called without arguments to produce a new value when a key is not present, in __getitem__ only. A defaultdict compares equal to a dict with the same items. All remaining arguments are treated the same as if they were passed to the dict constructor, including keyword arguments.

copy() a shallow copy of D.
default_factory

Factory for default value called by __missing__().

class deque

Bases: object

deque([iterable[, maxlen]]) –> deque object

A list-like sequence optimized for data accesses near its endpoints.

append()

Add an element to the right side of the deque.

appendleft()

Add an element to the left side of the deque.

clear()

Remove all elements from the deque.

copy()

Return a shallow copy of a deque.

count(value) integer -- return number of occurrences of value
extend()

Extend the right side of the deque with elements from the iterable

extendleft()

Extend the left side of the deque with elements from the iterable

index(value[, start[, stop]]) integer -- return first index of value.

Raises ValueError if the value is not present.

insert()

D.insert(index, object) – insert object before index

pop()

Remove and return the rightmost element.

popleft()

Remove and return the leftmost element.

remove()

D.remove(value) – remove first occurrence of value.

reverse()

D.reverse() – reverse IN PLACE

rotate()

Rotate the deque n steps to the right (default n=1). If n is negative, rotates left.

maxlen

maximum size of a deque or None if unbounded

namedtuple(typename, field_names, *, rename=False, defaults=None, module=None)

Returns a new subclass of tuple with named fields.

>>> Point = namedtuple('Point', ['x', 'y'])
>>> Point.__doc__                   # docstring for the new class
'Point(x, y)'
>>> p = Point(11, y=22)             # instantiate with positional args or keywords
>>> p[0] + p[1]                     # indexable like a plain tuple
33
>>> x, y = p                        # unpack like a regular tuple
>>> x, y
(11, 22)
>>> p.x + p.y                       # fields also accessible by name
33
>>> d = p._asdict()                 # convert to a dictionary
>>> d['x']
11
>>> Point(**d)                      # convert from a dictionary
Point(x=11, y=22)
>>> p._replace(x=100)               # _replace() is like str.replace() but targets named fields
Point(x=100, y=22)