atomica.utils.NDict

class atomica.utils.NDict(*args, **kwargs)[source]

Bases: odict

Store and sync items with a name property

Combine the init properties of both OrderedDict and defaultdict

Methods

append

Support an append method, like a list

clear

Reset to an empty odict

copy

Copy an item and return the copy

disp

Print out flexible representation, short by default.

enumitems

Returns tuple of 3 things: index, key, value.

enumkeys

Shortcut for enumerate(odict.keys()).

enumvals

Shortcut for enumerate(odict.values())

enumvalues

Alias for enumvals().

export

Export the odict in a form that is valid Python code

filter

Filter the odict keys and return a new odict which is a subset.

filtervals

Like filter, but filters by value rather than key

findbykey

Same as findkeys, but returns values instead

findbyval

Returns the key(s) that match a given value -- reverse of findbykey, except here uses exact matches to the value or values provided.

findkeys

Find all keys that match a given pattern.

fromeach

Take a "slice" across all the keys of an odict, applying the same operation to entry.

fromkeys

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

get

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

getnested

Alias to sc.getnested(odict); see sc.makenested() for full documentation.

index

Return the index of a given key

insert

Function to do insert a key -- note, computationally inefficient.

items

Return a list of items (as in Python 2).

iteritems

Alias to items()

iternested

Alias to sc.iternested(odict); see sc.makenested() for full documentation.

keys

Return a list of keys (as in Python 2), not a dict_keys object.

make

An alternate way of making or adding to an odict.

makefrom

Create an odict from entries in another dictionary.

makenested

Alias to sc.makenested(odict); see sc.makenested() for full documentation.

map

Apply a function to each element of the odict, returning a new odict with the same keys.

move_to_end

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

pop

Allows pop to support strings, integers, slices, lists, or arrays

popitem

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

promote

Like promotetolist, but for odicts.

remove

Remove an item by key and do not return it

rename

Change a key name -- WARNING, very inefficient!

reverse

Reverse the order of an odict

reversed

Shortcut for making a copy of the sorted odict

setdefault

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

setitem

Use regular dictionary setitem, rather than odict's

setnested

Alias to sc.setnested(odict); see sc.makenested() for full documentation.

sort

Create a sorted version of the odict.

sorted

Shortcut for making a copy of the sorted odict -- see sort() for options

toeach

The inverse of fromeach: partially reset elements within each odict key.

update

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]

valind

Return the index of a given value

values

Return a list of values (as in Python 2).

__add__(dict2)

Allow two dictionaries to be added (merged).

Example:

dict1 = sc.odict(a=3, b=4)
dict2 = sc.odict(c=5, d=7)
dict3 = dict1 + dict2
append(value)[source]

Support an append method, like a list

clear()

Reset to an empty odict

copy(old, new)[source]

Copy an item and return the copy

Parameters
  • old – The key of the existing item

  • new – The new name for the item

Returns

The copied item

Example usage: >>> new_parset = proj.parsets.copy(‘old_name’,’new_name’)

disp(maxlen=None, showmultilines=True, divider=False, dividerthresh=10, numindents=0, sigfigs=5, numformat=None, maxitems=20, **kwargs)

Print out flexible representation, short by default.

Example:

z = sc.odict().make(keys=['a','b','c'], vals=[4.293487,3,6])
z.disp(sigfigs=3)
z.disp(numformat='%0.6f')
enumitems(transpose=False)

Returns tuple of 3 things: index, key, value.

If transpose=True, return a tuple of lists rather than a list of tuples.

enumkeys(transpose=False)

Shortcut for enumerate(odict.keys()).

If transpose=True, return a tuple of lists rather than a list of tuples.

enumvals(transpose=False)

Shortcut for enumerate(odict.values())

If transpose=True, return a tuple of lists rather than a list of tuples.

enumvalues(transpose=False)

Alias for enumvals(). New in version 1.2.0.

export(doprint=True)

Export the odict in a form that is valid Python code

filter(keys=None, pattern=None, method=None, exclude=False)

Filter the odict keys and return a new odict which is a subset. If keys is a list, then uses that for matching. If the first argument is a string, then treats as a pattern for matching using findkeys(). If exclude=True, then will exclude rather than include matches.

filtervals(value)

Like filter, but filters by value rather than key

findbykey(pattern=None, method=None, first=True)

Same as findkeys, but returns values instead

findbyval(value, first=True, strict=False)

Returns the key(s) that match a given value – reverse of findbykey, except here uses exact matches to the value or values provided.

Example:

z = odict({'dog':[2,3], 'cat':[4,6], 'mongoose':[4,6]})
z.findvals([4,6]) # returns 'cat'
z.findvals([4,6], first=False) # returns ['cat', 'mongoose']
findkeys(pattern=None, method=None, first=None)

Find all keys that match a given pattern. By default uses regex, but other options are ‘find’, ‘startswith’, ‘endswith’. Can also specify whether or not to only return the first result (default false). If the key is a tuple instead of a string, it will search each element of the tuple.

fromeach(ind=None, asdict=True)

Take a “slice” across all the keys of an odict, applying the same operation to entry. The simplest usage is just to pick an index. However, you can also use it to apply a function to each key.

Example:

z = odict({'a':array([1,2,3,4]), 'b':array([5,6,7,8])})
z.fromeach(2) # Returns array([3,7])
z.fromeach(ind=[1,3], asdict=True) # Returns odict({'a':array([2,4]), 'b':array([6,8])})
fromkeys(value=None)

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

get(key, default=None, /)

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

getnested(*args, **kwargs)

Alias to sc.getnested(odict); see sc.makenested() for full documentation. New in version 1.2.0.

index(value)

Return the index of a given key

insert(pos=None, key=None, value=None)

Function to do insert a key – note, computationally inefficient.

Example:

z = odict()
z['foo'] = 1492
z.insert(1604)
z.insert(0, 'ganges', 1444)
z.insert(2, 'meikang', 1234)
items(transpose=False)

Return a list of items (as in Python 2).

iteritems(transpose=False)

Alias to items()

iternested(*args, **kwargs)

Alias to sc.iternested(odict); see sc.makenested() for full documentation. New in version 1.2.0.

keys()

Return a list of keys (as in Python 2), not a dict_keys object.

make(keys=None, vals=None, keys2=None, keys3=None, coerce='full')

An alternate way of making or adding to an odict.

Parameters
  • keys (list/int) – the list of keys to use

  • vals (list/arr) – the list of values to use

  • keys2 (list/int) – for a second level of nesting

  • keys3 (list/int) – for a third level of nesting

  • coerce (str) – what types to coerce into being separate dict entries

Examples:

a = sc.odict().make(5) # Make an odict of length 5, populated with Nones and default key names
b = sc.odict().make('foo',34) # Make an odict with a single key 'foo' of value 34
c = sc.odict().make(['a','b']) # Make an odict with keys 'a' and 'b'
d = sc.odict().make(['a','b'], 0) # Make an odict with keys 'a' and 'b', initialized to 0
e = sc.odict().make(keys=['a','b'], vals=[1,2]) # Make an odict with 'a':1 and 'b':2
f = sc.odict().make(keys=['a','b'], vals=np.array([1,2])) # As above, since arrays are coerced into lists
g = sc.odict({'a':34, 'b':58}).make(['c','d'],[99,45]) # Add extra keys to an exising odict
h = sc.odict().make(keys=['a','b','c'], keys2=['A','B','C'], keys3=['x','y','z'], vals=0) # Make a triply nested odict

New in version 1.2.2: “coerce” argument

static makefrom(source=None, include=None, keynames=None, force=True, *args, **kwargs)

Create an odict from entries in another dictionary. If keys is None, then use all keys from the current dictionary.

Parameters
  • source (dict/list/etc) – the item(s) to convert to an odict

  • include (list) – list of keys to include from the source dict in the odict (default: all)

  • keynames (list) – names of keys if source is not a dict

  • force (bool) – whether to force conversion to an odict even if e.g. the source has numeric keys

Examples:

a = 'cat'
b = 'dog'
o = sc.odict.makefrom(source=locals(), include=['a','b']) # Make use of fact that variables are stored in a dictionary

d = {'a':'cat', 'b':'dog'}
o = sc.odict.makefrom(d) # Same as odict(d)
l = ['cat', 'monkey', 'dog']
o = sc.odict.makefrom(source=l, include=[0,2], keynames=['a','b'])

d = {12:'monkeys', 3:'musketeers'}
o = sc.odict.makefrom(d)
makenested(*args, **kwargs)

Alias to sc.makenested(odict); see sc.makenested() for full documentation. New in version 1.2.0.

map(func=None)

Apply a function to each element of the odict, returning a new odict with the same keys.

Example:

cat = odict({'a':[1,2], 'b':[3,4]})
def myfunc(mylist): return [i**2 for i in mylist]
dog = cat.map(myfunc) # Returns odict({'a':[1,4], 'b':[9,16]})
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(key, *args, **kwargs)

Allows pop to support strings, integers, slices, lists, or arrays

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.

static promote(obj=None)

Like promotetolist, but for odicts.

Example:

od = sc.odict.promote(['There','are',4,'keys'])

Note, in most cases sc.odict(obj) or sc.odict().make(obj) can be used instead.

remove(key, *args, **kwargs)

Remove an item by key and do not return it

rename(oldkey, newkey)

Change a key name – WARNING, very inefficient!

reverse(copy=False)

Reverse the order of an odict

reversed()

Shortcut for making a copy of the sorted odict

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.

setitem(key, value)

Use regular dictionary setitem, rather than odict’s

setnested(*args, **kwargs)

Alias to sc.setnested(odict); see sc.makenested() for full documentation. New in version 1.2.0.

sort(sortby=None, reverse=False, copy=False, verbose=True)

Create a sorted version of the odict. Sorts by order of sortby, if provided, otherwise alphabetical. If copy is True, then returns a copy (like sorted()).

Note that you can also use this to do filtering.

sorted(sortby=None, reverse=False)

Shortcut for making a copy of the sorted odict – see sort() for options

toeach(ind=None, val=None)

The inverse of fromeach: partially reset elements within each odict key.

Example:

z = odict({'a':[1,2,3,4], 'b':[5,6,7,8]})
z.toeach(2, [10,20])    # z is now odict({'a':[1,2,10,4], 'b':[5,6,20,8]})
z.toeach(ind=3,val=666) #  z is now odict({'a':[1,2,10,666], 'b':[5,6,20,666]})
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]

valind(value)

Return the index of a given value

values()

Return a list of values (as in Python 2).