Converts a native Python dictionary to a raw DynamoDB item.

    :param dict item: Native item
    :returns: DynamoDB item
    :rtype: dict
483779
def dict_to_ddb(item):
    # type: (Dict[str, Any]) -> Dict[str, Any]
    # TODO: narrow these types down
    
    serializer = TypeSerializer()
    return {key: serializer.serialize(value) for key, value in item.items()}
450555
def normalize_dict(dictionary, **kwargs):
    
    result = {}
    if isinstance(dictionary, dict):
        keys = list(dictionary.keys())
        for key in keys:
            result[normalizer(key, **kwargs)] = normalize_dict(dictionary.get(key), **kwargs)
    else:
        result = dictionary
    return result
878386
def load_items(self, items):
        
        loaded_items = {}
        requests = collections.deque(create_batch_get_chunks(items))
        while requests:
            request = requests.pop()
            try:
                response = self.dynamodb_client.batch_get_item(RequestItems=request)
            except botocore.exceptions.ClientError as error:
                raise BloopException("Unexpected error while loading items.") from error

            # Accumulate results
            for table_name, table_items in response.get("Responses", {}).items():
                loaded_items.setdefault(table_name, []).extend(table_items)

            # Push additional request onto the deque.
            # "UnprocessedKeys" is {} if this request is done
            if response["UnprocessedKeys"]:
                requests.append(response["UnprocessedKeys"])
        return loaded_items
1023713
def from_dict(cls, database, key, data, clear=False):
        
        hsh = cls(database, key)
        if clear:
            hsh.clear()
        hsh.update(data)
        return hsh
1006787
def fromDict(cls, data):
        
        obj = cls()
        obj.raw = data
        for name, value in data.iteritems():
            if cls.SIMPLE_PROPS and name in cls.SIMPLE_PROPS:
                setattr(obj, name, value)
            elif cls.COMPLEX_PROPS and name in cls.COMPLEX_PROPS:
                value = cls.COMPLEX_PROPS[name].fromDict(value)
                setattr(obj, name, value)
            elif cls.LIST_PROPS and name in cls.LIST_PROPS:
                value = [cls.LIST_PROPS[name].fromDict(item)
                         for item in value]
                setattr(obj, name, value)

        return obj
1083840
def dict_to_serialized_dict(ref, the_dict):
    
    result = {}
    for elt in list(the_dict.values()):
        if not getattr(elt, 'serialize', None):
            continue
        result[elt.uuid] = elt.serialize()
    return result
1261466
def unpack_from_dynamodb(*, attrs, expected, model=None, obj=None, engine=None, context=None, **kwargs):
    """"""
    context = context or {"engine": engine}
    engine = engine or context.get("engine", None)
    if not engine:
        raise ValueError("You must provide engine or a context with an engine.")
    if model is None and obj is None:
        raise ValueError("You must provide a model or obj to unpack.")
    if model is not None and obj is not None:
        raise ValueError("Only specify model or obj.")
    if model:
        obj = model.Meta.init()

    for column in expected:
        value = attrs.get(column.dynamo_name, None)
        value = engine._load(column.typedef, value, context=context, **kwargs)
        setattr(obj, column.name, value)
    return obj
1081125
def asdict(self, name, _type=None, _set=False):
        

        if _type is None:
            _type = lambda t: t

        dict_str = self.pop(name, None)
        if not dict_str:
            return {}

        _dict = {}
        for item in split_strip(dict_str):
            key, _, val = item.partition(':')
            val = _type(val)
            if key in _dict:
                if isinstance(_dict[key], list):
                    _dict[key].append(val)
                else:
                    _dict[key] = [_dict[key], val]
            else:
                _dict[key] = val

        if _set:
            self[name] = _dict

        return _dict
102125
def convert_dict(d, cls=AttrDict): # not used
    '''
    
    '''
    for k, v in d.items():
        if isinstance(v, Mapping):
            d[k] = convert_dict(v)
        elif isinstance(v, list):
            for i, e in enumerate(v):
                if isinstance(e, Mapping):
                    v[i] = convert_dict(e)
    return cls(d)
1082234
def _from_dict_dict(cls, dic):
        
        return cls({_convert_id(i): v for i, v in dic.items()})
726661
def save_item(self, item):
        
        try:
            self.dynamodb_client.update_item(**item)
        except botocore.exceptions.ClientError as error:
            handle_constraint_violation(error)
371295
def deserialize_durable_record_to_current_model(record, current_model):
    
    # Was the item in question too big for SNS? If so, then we need to fetch the item from the current Dynamo table:
    if record.get(EVENT_TOO_BIG_FLAG):
        # Try to get the data from the current table vs. grabbing the data from the Durable table:
        return get_full_current_object(record['dynamodb']['Keys']['arn']['S'], current_model)

    new_image = remove_durable_specific_fields(record['dynamodb']['NewImage'])
    data = {}

    for item, value in new_image.items():
        # This could end up as loss of precision
        data[item] = DESER.deserialize(value)

    return current_model(**data)
613120
def deserialize_current_record_to_durable_model(record, current_model, durable_model):
    
    # Was the item in question too big for SNS? If so, then we need to fetch the item from the current Dynamo table:
    if record.get(EVENT_TOO_BIG_FLAG):
        record = get_full_current_object(record['dynamodb']['Keys']['arn']['S'], current_model)

        if not record:
            return None

        serialized = record._serialize()  # pylint: disable=W0212

        record = {
            'dynamodb': {
                'NewImage': serialized['attributes']
            }
        }

        # The ARN isn't added because it's in the HASH key section:
        record['dynamodb']['NewImage']['arn'] = {'S': serialized['HASH']}

    new_image = remove_current_specific_fields(record['dynamodb']['NewImage'])
    data = {}

    for item, value in new_image.items():
        # This could end up as loss of precision
        data[item] = DESER.deserialize(value)

    return durable_model(**data)
109746
def _to_dict(self, serialize=False):
        
        copy_dict = self.__dict__.copy()
        for key, value in vars(self).items():
            # We want to send all ids to Zendesk always
            if serialize and key == 'id':
                continue

            # If this is a Zenpy object, convert it to a dict.
            if not serialize and isinstance(value, BaseObject):
                copy_dict[key] = copy_dict.pop(key).to_dict()

            # This object has a flag indicating it has been dirtied, so we want to send it off.
            elif serialize and getattr(value, '_dirty', False):
                continue

            # Here we have an attribute that should always be sent to Zendesk.
            elif serialize and key in self._always_dirty:
                continue

            # These are for internal tracking, so just delete.
            elif key in ('api', '_dirty_attributes', '_always_dirty', '_dirty_callback', '_dirty'):
                del copy_dict[key]

            # If the attribute has not been modified, do not send it.
            elif serialize and key not in self._dirty_attributes:
                del copy_dict[key]

            # Some reserved words are prefixed with an underscore, remove it here.
            elif key.startswith('_'):
                copy_dict[key[1:]] = copy_dict[key]
                del copy_dict[key]
        return copy_dict
647767
def get_stats_item(self, item):
        
        if isinstance(self.stats, dict):
            try:
                return self._json_dumps({item: self.stats[item]})
            except KeyError as e:
                logger.error("Cannot get item {} ({})".format(item, e))
                return None
        elif isinstance(self.stats, list):
            try:
                # Source:
                # http://stackoverflow.com/questions/4573875/python-get-index-of-dictionary-item-in-list
                # But https://github.com/nicolargo/glances/issues/1401
                return self._json_dumps({item: list(map(itemgetter(item), self.stats))})
            except (KeyError, ValueError) as e:
                logger.error("Cannot get item {} ({})".format(item, e))
                return None
        else:
            return None
273682
def show_item_dict(self, item):
        """"""
        d = {}
        for col in self.show_columns:
            v = getattr(item, col)
            if not isinstance(v, (int, float, string_types)):
                v = str(v)
            d[col] = v
        return d
491932
def to_dict(self, val=UNSET):
        
        if val is UNSET:
            val = self

        if isinstance(val, dict2) or isinstance(val, dict):
            res = dict()
            for k, v in val.items():
                res[k] = self.to_dict(v)
            return res
        elif isinstance(val, list):
            res = []
            for item in val:
                res.append(self.to_dict(item))
            return res
        else:
            return val