Toolshed: types : XDict¶
Import XDict¶
from Naked.toolshed.types import XDict
Import XDict from C Module¶
from Naked.toolshed.c.types import XDict
The C module must be compiled before you import it. See the naked build documentation for more information.
Description¶
The XDict class is an extension of the Python dictionary type. You can use all built-in Python dictionary methods with it. It extends the built-in Python dictionary type with operator overloads, metadata definitions on instantiation, preservation of metadata on conversion to other types (with included XDict methods), and a number of additional dictionary methods.
The XDict supports equality testing based upon both the dictionary data as well as the supplemental metadata (if included). You can use the == and != operators to perform this testing (or alternatively, the XDict.equals() method).
-
class
Naked.toolshed.types.XDict(the_dictionary[, attribute_dictionary])¶ A
XDictis instantiated with a Python dictionary. You have the option to include a second Python dictionary to include additional metadata. The metadata are stored as attributes on theXDictwith dictionary keys mapped to attribute names and dictionary values mapped to the corresponding attribute values.Parameters: - the_dictionary (dictionary) – the data that are used to create an instance of a
XDictdictionary. - attribute_dictionary (dictionary) – (optional) a Python dictionary that is used to define the attributes of a new instance of a
XDict. Key names are mapped to attribute names and their corresponding values are mapped to the attribute values.
Overloaded Operators
-
__add__(other_dictionary)¶ The
+operator is overloaded to update theXDictwith new key:value pairs from a Python dictionary or anotherXDict. AnXDictmust be the left sided operand in this statement as standard Python dictionaries do not support this form of dictionary combination. When used with a Python dictionary, the key:value pairs in the Python dictionary are added to theXDictdictionary. When used with anotherXDict, the key:value pairs from theXDictparameter are defined in theXDictdictionary and the attributes from theXDictparameter are defined in theXDict. The parameter dictionary definitions take precedence for key:value and attributes on the returnedXDictwhen both objects contain the same dictionary key or attribute name.Parameters: other_dictionary (dictionary) – a Python dictionary or XDictReturns: (XDict) returns the original XDict updated with data in the other_dictionaryas defined above
-
__iadd__(other_dictionary)¶ The
+=operator is overloaded to update theXDictoperand on the left side of the operator with the Python dictionary orXDicton the right side of the operator. The update takes place as defined in the description of the__add__()method above.Returns: (XDict) returns a XDictthat is updated with the data in the right sided operand.
-
__eq__(other_dictionary)¶ The
==operator is overloaded to perform equality testing as defined for theequals()method below.Returns: (boolean) True= conditions for equality are met;False= conditions for equality are not met
-
__neq__(other_dictionary)¶ The
!=operator is overloaded to return the negation of the test for equality as it is defined in theequals()method below.Returns: (boolean) True= conditions for equality are not met;False= conditions for equality are met
Key Methods
-
difference(other_dictionary)¶ Returns the set of dictionary keys in the
XDictthat are not included in theother_dictionaryparameter.Parameters: other_dictionary (dictionary) – a Python dictionary or XDictReturns: (set) Returns a set of dictionary key strings that meet this definition. Returns an empty set if there are no keys that meet the definition.
-
intersection(other_dictionary)¶ Returns the set of dictionary keys in the
XDictthat are also included in theother_dictionaryparameter.Parameters: other_dictionary (dictionary) – a Python dictionary or XDictReturns: (set) Returns a set of dictionary key strings tha meet this definition. Returns an empty set if there are no keys that meet the definition.
-
key_xlist()¶ Returns a
XListcontaining the keys in theXDictwith preservation of theXDictattribute metadata in the returnedXList.Returns: (XList) returns a XList that contains the XDictkeys mapped to list items. The attribute data in theXDictis preserved in the returnedXList.
Value Methods
-
conditional_map_to_vals(conditional_func, map_func)¶ Map a function parameter
map_functo everyXDictvalue that has a key that returnsTruewhen the key is passed as a parameter to theconditional_funcfunction. EveryXDictkey is tested in theconditional_func.Parameters: - conditional_func (function) – a function that accepts a
XDictkey as the first parameter and returns a boolean value. When the returned value isTrue, the value associated with this key is passed as the first parameter to themap_func. - map_func (function) – a function that accepts a
XDictvalue as the first parameter and returns the object that will be used to update the value definition for the key in the returnedXDict.
Returns: (XDict) returns the
XDictwith values that are updated as defined by theconditional_funcandmap_funcprocessing. If themap_funcdoes not return a value, the associated key is defined withNone. If you intend to maintain the original value, return the value that was passed as the parameter to the function.- conditional_func (function) – a function that accepts a
-
map_to_vals(map_func)¶ Maps a function parameter
map_functo every value in theXDict. Every value in theXDictis passed to this function.Parameters: map_func (function) – a function that accepts a XDictvalue and returns the object that will be used to update the value definition for the key in the returnedXDictReturns: (XDict) returns the XDictwith values that are updated as defined by the returned values from themap_func. If themap_funcdoes not return a value, the associated key is defined withNone. If you intend to maintain the original value, return the value that was passed as the parameter to the function.
-
max_val()¶ Returns a 2-item tuple containing the maximum value and associated key as defined by the Python built-in
max()function.Returns: (tuple) returns a 2-item tuple that includes ( max value,key). The maximum numeric value is returned for numeric types. The value at the top of the reverse alphabetic order is returned for strings. For other types, the returned value is defined by the Python built-inmax()function (if supported).
-
min_val()¶ Returns a 2-item tuple containing the minimum value and associated key as defined by the Python built-in
min()function.Returns: (tuple) returns a 2-item tuple that includes ( min value,key). The minimum numeric value is returned for numeric types. The value at the top of the alphabetic order is returned for strings. For other types, the returned value is as defined for the Python built-inmax()function (if supported).
-
sum_vals()¶ Returns the sum of the values as determined by the Python built-in
sum()function.Returns: (numeric) returns the sum as a numeric type defined by the input types Raises: TypeErrorfor unsupported operand types encountered as values in theXDict
-
val_count(the_value)¶ Returns the count of
the_valuevalues in theXDict. Values are counted if they meet the criterionXDict()[key] == the_value.Parameters: the_value (object) – the value type and definition to be counted in the XDictReturns: (integer) returns the count of the_valuein theXDictas an integer.
-
val_count_ci(the_value)¶ Returns the count of a case-insensitive test for
the_valuestring in theXDictvalues. This method can be used withXDictthat include value types that do not support thestring.lower()method that is used in the case-insensitive testing.Parameters: the_value (string) – the string value that is to be used for a case-insensitive count across all XDictvaluesReturns: (integer) returns the count of strings that match the_valuein a case-insensitive test.
-
val_xlist()¶ Returns a
XListthat contains theXDictvalues mapped to list items.Returns: (XList) returns a XListthat containsXDictvalues that are mapped to list items. Any attribute metadata from the originalXDictis maintained in the returnedXList.
Other Methods
-
equals(other_object)¶ The
equals()method performs equality testing between aXDictand another object. The==operator can also be used to perform this test between the left (XDict) and right (other_object) sided operands. Equality testing is defined by meeting the criteria: (1) the type of theXDictand theother_objectare the same; (2) the dictionary keys and values are the same in theXDictand theother_object; (3) the attribute metadata (if present) are the same in theXDictand theother_object.Parameters: other_object (object) – an object that is to be tested for equality Returns: (boolean) True= conditions for equality are met;False= conditions for equality are not met
-
random()¶ Returns a single, random key:value pair as a Python dictionary. The random pair is identified with the Python
random.sample()method.Returns: (dictionary) a Python dictionary that contains a single key:value pair
-
random_sample(number)¶ Returns
numberrandom key:value pair(s) in a Python dictionary. The random pairs are identified with the Pythonrandom.sample()method. The random sampling is performed without replacement.Parameters: number (integer) – the number of random key:value pairs to return Returns: (dictionary) a Python dictionary that contains numberkey:value pairs
-
xitems()¶ A generator that yields 2-item tuples of key:value pairs from the
XDict. This utilizes thedict.iteritems()generator when the Python 2 interpreter is used and thedict.items()generator when the Python 3 interpreter is used.Returns: (tuple) yields a 2-item tuple (key, value)on each iteration. Iteration ends when allXDictkey:value pairs have been returned.
-
type()¶ Return the type of the
XDictobject.Returns: (type) returns the type of the XDict
- the_dictionary (dictionary) – the data that are used to create an instance of a
Examples¶
Create a New Instance of XDict, No Metadata
from Naked.toolshed.types import XDict
xd = XDict({'name': 'Guido', 'language': 'python'})
Create a New Instance of XDict, With Metadata
from Naked.toolshed.types import XDict
xd = XDict({'name': 'Guido', 'language': 'python'}, {'dict_type': 'dev'})
Access XDict Value
from Naked.toolshed.types import XDict
xd = XDict({'name': 'Guido', 'language': 'python'}, {'dict_type': 'dev'})
print(xd['name']) # prints 'Guido'
print(xd['language']) # prints 'python'
Access XDict Attribute
from Naked.toolshed.types import XDict
xd = XDict({'name': 'Guido', 'language': 'python'}, {'dict_type': 'dev'})
print(xd.dict_type) # prints 'dev'
Compare XDict, Different Dictionaries
from Naked.toolshed.types import XDict
xd1 = XDict({'name': 'Guido', 'language': 'python'}, {'dict_type': 'dev'})
xd2 = XDict({'name': 'Yukihiro', 'language': 'ruby'}, {'dict_type': 'dev'})
print(xd1 == xd2) # prints False
print(xd != xd2) # prints True
Compare XDict, Different Attributes
from Naked.toolshed.types import XDict
xd1 = XDict({'name': 'Guido', 'language': 'python'}, {'dict_type': 'dev'})
xd2 = XDict({'name': 'Guido', 'language': 'python'}, {'rating': 1})
print(xd1 == xd2) # prints False
print(xd != xd2) # prints True
Update XDict with Dictionary
from Naked.toolshed.types import XDict
xd = XDict({'name': 'Guido', 'language': 'python'}, {'dict_type': 'dev'})
py_dict = {'year': 1991}
xd_with_year = xd + py_dict
print(xd_with_year) # prints {'name': 'Guido', 'language': 'python', 'year': 1991}
print(xd.dict_type) # prints 'dev'
Update XDict with XDict
from Naked.toolshed.types import XDict
xd1 = XDict({'name': 'Guido', 'language': 'python'}, {'dict_type': 'dev'})
xd2 = XDict({'year': 1991}, {'includes': 'year'})
xd3 = xd1 + xd2
print(xd3) # prints {'name': 'Guido', 'language': 'python', 'year': 1991}
print(xd3.dict_type) # prints 'dev'
print(xd3.includes) # prints 'year'
Update XDict with XDict, Alternate Approach with += Overload
from Naked.toolshed.types import XDict
xd1 = XDict({'name': 'Guido', 'language': 'python'}, {'dict_type': 'dev'})
xd2 = XDict({'year': 1991}, {'includes': 'year'})
xd1 += xd2
print(xd1) # prints {'name': 'Guido', 'language': 'python', 'year': 1991}
print(xd1.dict_type) # prints 'dev'
print(xd1.includes) # prints 'year'
Make XList from XDict Keys
from Naked.toolshed.types import XDict
xd = XDict({'name': 'Guido', 'language': 'python'}, {'dict_type': 'dev'})
xl = xd.key_xlist()
print(xl) # prints ['name', 'language']
print(xl.dict_type) # prints 'dev'
Make XList from XDict Values
from Naked.toolshed.types import XDict
xd = XDict({'name': 'Guido', 'language': 'python'}, {'dict_type': 'dev'})
xl = xd.val_xlist()
print(xl) # prints ['Guido', 'python']
print(xl.dict_type) # prints 'dev'
Conditional Mapping of a Function to XDict Values
from Naked.toolshed.types import XDict
def spam_corrector(the_argument):
if the_argument == 'eggs':
pass
else:
return 'eggs'
def comp_detector(the_argument):
if the_argument == 'complements':
return True
else:
return False
xd = XDict({'food': 'spam', 'complements': 'sausage'})
xd = xd.conditional_map_to_vals(comp_detector, spam_corrector)
print(xd) # prints {'food': 'spam', 'complements': 'eggs'}