嵌套列表到有序的字典

时间:2017-11-08 02:38:46

标签: python list dictionary

我有一个像

这样的嵌套列表
seq = [ [['a'], ['b', 'c']], ['d'], ['e', 'f']]

我想将其转换为有序字典,如

seq_order_dict = { '0_0_0': ['a'],
                   '0_0_1': ['b', 'c'],
                   '1_0': ['d'],
                   '2_0': ['e', 'f']}

要求是

  1. seq_order_dict['2_0']会从之前的seq_order_dict['1_0']项中获取一些信息来做某事。
  2. 如果seq_order_dict['1_0']上一项seq_order_dict['0_0']不存在,seq_order_dict['1_0']seq_order_dict['0_0_x']做某事。 (x = 0,1,2,...)
  3. 我的斗智尽头......

1 个答案:

答案 0 :(得分:1)

即使这个解决方案不符合所有要求,也许会接受这个解决方案:

import collections


seq = [[['a'], ['b', 'c']], ['d'], ['e', 'f']]


def flatten(d, parent_key='', sep='_'):
    flatten_dict = collections.OrderedDict()

    for k, v in d.items():
        new_key = str(parent_key) + str(sep) + str(k) if parent_key else str(k)
        if isinstance(v, collections.MutableMapping):
            flatten_dict.update(flatten(v, new_key, sep=sep))
        else:
            flatten_dict[new_key] = v

    return flatten_dict

def list_to_dict(seq):
    if isinstance(seq, list) and all(isinstance(x, list) for x in seq):
        nested_dict = collections.OrderedDict()
        for i, item in enumerate(seq):
            nested_dict[i] = list_to_dict(item)
        return flatten(nested_dict)
    return seq


print(list_to_dict(seq))

而不是{ '0_0_0': ['a'], '0_0_1': ['b', 'c'], ... } if会产生以下内容:

OrderedDict([('0_0', ['a']), ('0_1', ['b', 'c']), ('1', ['d']), ('2', ['e', 'f'])])