将字典转换为列表

Neo*_*eox 10 python dictionary list

例:

something = {
    "1": {
        "2": {
            "3": {
                "4": {},
                "5": {},
                "7": {},
                },
            "8": {
                "9": {},
                "10": {}
            },
            "11": {
                "12": {
                    "13": {
                        "14": {
                            "15": {
                                "16": {
                                    "17": {
                                        "18": {}
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我正在尝试将此字典转换为这样的项目列表:

['1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18']
Run Code Online (Sandbox Code Playgroud)

我应该使用什么方法?

我已经尝试过something.items(),但我得到的是:

[('1', {'2': {'11': {'12': {'13': {'14': {'15': {'16': {'17': {'18': {}}}}}}}}, '8': {'9': {}, '10': {}}, '3': {'5': {}, '4': {}, '7': {}}}})]
Run Code Online (Sandbox Code Playgroud)

这是我第一次在这里发帖,所以如果我做错了请告诉我.

谢谢,抱歉这个奇怪的帖子.

Mar*_*ers 24

你需要使用一个函数来展平你的结构:

def flatten(d):
    for key, value in d.iteritems():
        yield key
        for sub in flatten(value):
            yield sub
Run Code Online (Sandbox Code Playgroud)

(如果您使用的是Python 3 ,.iteritems()则应替换它.items()).

在python 3.3及更高版本上,您还可以使用新yield from语法:

def flatten(d):
    for key, value in d.items():
        yield key
        yield from flatten(value)
Run Code Online (Sandbox Code Playgroud)

这将递归地产生所有键.要将其转换为列表,请使用:

list(flatten(elements))
Run Code Online (Sandbox Code Playgroud)

由于Python字典是无序的,因此返回的键的顺序不会被排序.如果您希望密钥具有特定的排序,则必须对结果进行显式排序.


eum*_*iro 6

something = {'1': {'2': {'11': {'12': {'13': {'14': {'15': {'16': {'17': {'18': {}}}}}}}}, '3': {'4': {}, '5': {}, '7': {}}, '8': {'10': {}, '9': {}}}}}
a = []

def flatten(d,a):
    for k,v in d.items():
        a.append(k)
        flatten(v, a)
flatten(something, a)

# a == ['1', '2', '11', '12', '13', '14', '15', '16', '17', '18', '8', '9', '10', '3', '5', '4', '7']"
Run Code Online (Sandbox Code Playgroud)