Expand a flattened dictionary.

    :param dict flat_dict: a nested dictionary that has been flattened so the keys are composite
    :param str sep: the separator between concatenated keys
    :rtype: dict
961281
def expand_dict(flat_dict, sep='_'):
    
    res = {}
    rdict = defaultdict(list)

    for flat_key, value in flat_dict.items():
        key = flat_key.split(sep, 1)
        if 1 == len(key):
            res[key[0]] = value
        else:
            rdict[key[0]].append((key[1:], value))

    for k, v in rdict.items():
        res[k] = expand_dict({ik: iv for (ik,), iv in v})

    return res
1200469
def flatten (d, *keys):
    
    flat = { }

    for k in keys:
        flat = merge(flat, d.pop(k, { }))

    return flat
314233
def dict_flat_generator(value, attname=None, splitter=JSPLITTER,
                        dumps=None, prefix=None, error=ValueError,
                        recursive=True):
    ''''''
    if not isinstance(value, dict) or not recursive:
        if not prefix:
            raise error('Cannot assign a non dictionary to a JSON field')
        else:
            name = '%s%s%s' % (attname, splitter,
                               prefix) if attname else prefix
            yield name, dumps(value) if dumps else value
    else:
        # loop over dictionary
        for field in value:
            val = value[field]
            key = prefix
            if field:
                key = '%s%s%s' % (prefix, splitter,
                                  field) if prefix else field
            for k, v2 in dict_flat_generator(val, attname, splitter, dumps,
                                             key, error, field):
                yield k, v2
1260645
def iterate_flattened(d):
    
    for key in sorted(d.keys()):
        value = d[key]
        if isinstance(value, dict) and value:
            for k, v in iterate_flattened(d[key]):
                yield join_paths(key, k), v
        else:
            yield key, value
931014
def _join(lst, key, sep=";"):
    
    return sep.join([d[key] for d in lst if d[key]])
965358
def flatten(data, parent_key='', sep='_'):
    
    items = []

    if isinstance(data, list):
        logger.debug('Flattening list {}'.format(data))
        list_keys = [str(i) for i in range(0, len(data))]
        items.extend(
            flatten(dict(zip(list_keys, data)), parent_key, sep=sep).items())

    elif isinstance(data, dict):
        logger.debug('Flattening dict {}'.format(data))

        for key, value in data.items():
            new_key = parent_key + sep + key if parent_key else key
            if isinstance(value, collections.MutableMapping):
                items.extend(flatten(value, new_key, sep=sep).items())
            else:
                if isinstance(value, list):
                    list_keys = [str(i) for i in range(0, len(value))]
                    items.extend(
                        flatten(
                            dict(zip(list_keys, value)), new_key, sep=sep).items())
                else:
                    items.append((new_key, value))
    else:
        logger.debug('Nothing to flatten with {}'.format(data))
        return data

    return collections.OrderedDict(items)
826210
def process_flattened(flattened):
    
    # Keep arrays in order.
    processed = OrderedDict()

    # Cache identifiers, to avoid minting a new ID for each field of the same object.
    identifiers = {}

    for key in flattened:
        new_key = []
        for end, part in enumerate(key, 1):
            # If this is a path to an item in an array.
            if isinstance(part, int):
                if key[:end] in identifiers:
                    part = identifiers[key[:end]]
                else:
                    # If it is an array of objects, get the `id` value to apply the identifier merge strategy.
                    # http://standard.open-contracting.org/latest/en/schema/merging/#identifier-merge
                    id_value = flattened.get(key[:end] + ('id',))

                    # If the object contained no top-level `id` value, set a unique value.
                    if id_value is None:
                        identifier = uuid.uuid4()
                    else:
                        identifier = id_value

                    # Save the original value. (If the value is an integer, this avoids coercing it to a string.)
                    part = IdValue(identifier)
                    part.original_value = id_value

                    identifiers[key[:end]] = part
            new_key.append(part)
        processed[tuple(new_key)] = flattened[key]

    return processed
327883
def flattened(self):
        
        flatx = {}
        flatf = {}
        for i in self.res:
            if isinstance(i, int):
                flatx[i] = []
                flatf[i] = []
                for x in sorted(self.res[i]):
                    for d in sorted(self.res[i][x]):
                        flatx[i].append(x)
                        flatf[i].append(d)
        return flatx, flatf
997064
def compose_sep(deps, separator):
        
        result = {}
        for dep in deps:
            if dep.name not in result:
                result[dep.name] = separator.join([op + ver for op, ver in dep.spec])
            else:
                result[dep.name] += separator + separator.join([op + ver for op, ver in dep.spec])
        return result
1014447
def flatten_multidict(multidict):
    """"""
    return dict([(key, value if len(value) > 1 else value[0])
                 for (key, value) in multidict.iterlists()])
464964
def flatten_dict(source, ancestors=None):
  """"""
  if not ancestors:
    ancestors = ()
  for key in source:
    if isinstance(source[key], dict):
      yield from flatten_dict(source[key], ancestors + (key, ))
    else:
      yield (ancestors + (key, ), source[key])
734833
def nested_set_dict(d, keys, value):
    
    assert keys
    key = keys[0]
    if len(keys) == 1:
        if key in d:
            raise ValueError("duplicated key '{}'".format(key))
        d[key] = value
        return
    d = d.setdefault(key, {})
    nested_set_dict(d, keys[1:], value)
1125851
function flatten(source, opts) {
  opts = opts || {};
  var delimiter = opts.delimiter = opts.delimiter || '.';
  var o = {};
  function iterate(source, parts) {
    var k, v;
    parts = parts || [];
    for(k in source) {
      v = source[k];
      if(v && typeof v === 'object' && Object.keys(v).length) {
        iterate(v, parts.concat(k));
      }else{
        o[parts.concat(k).join(delimiter)] = v;
      }
    }
  }
  iterate(source);
  return o;
}
1334646
def flatten_choices_dict(choices):
    
    ret = OrderedDict()
    for key, value in choices.items():
        if isinstance(value, dict):
            # grouped choices (category, sub choices)
            for sub_key, sub_value in value.items():
                ret[sub_key] = sub_value
        else:
            # choice (key, display value)
            ret[key] = value
    return ret
694721
def flatten_dict_vals(dict_):
    
    if isinstance(dict_, dict):
        return dict([
            ((key, augkey), augval)
            for key, val in dict_.items()
            for augkey, augval in flatten_dict_vals(val).items()
        ])
    else:
        return {None: dict_}
577294
def _flatten(self, field, items, transform = None):
		
		
		# Retrieve the value for each item in the iterable
		values = [item[field] for item in items]
		
		# Flatten any nested lists
		flattened = []
		for value in values:
			flattened.extend([value] if isinstance(value, str) else value)
		
		# Apply any supplied transformation function
		return transform(flattened) if transform != None else flattened
120711
def format_dict(dic, format_list, separator=',', default_value=str):
    

    dic = collections.defaultdict(default_value, dic)

    str_format = separator.join(["{" + "{}".format(head) + "}" for head in format_list])

    return str_format.format(**dic)