嵌套列表到嵌套字典

时间:2019-04-25 17:19:33

标签: python python-3.x

这是我的第一篇文章,我的代码有一些问题。

我需要转换对象列表:

mylist=[
    [length, 1322, width, 850, high, 620, type, sedan, e, 55, f, 44],
    [length, 1400, width, 922, high, 650, type, truck, e, 85, f, 50]
]

放入这样的字典中:

mydic = {
    sedan : {length : 1322, width : 850, high : 620, type : sedan, e : 55, f : 44},
    truck : {length : 1400, width : 922, high : 650, type : truck, e : 85, f : 50}
}

我不知道该怎么做... 预先感谢!

2 个答案:

答案 0 :(得分:0)

lista=[["length", 1322, "width", 850, "high", 620, "type", "sedan", "e", 55, "f", 44], ["length", 1400, "width", 922, "high", 650, "type", "truck", "e", 85, "f", 50]]

b=[{q:i[w*2+1] for w,q in enumerate(i[::2])} for i in lista] # Goes through the list and put the key and keyvalue together in the future nested dict

c={i["type"]:i for i in b} #creates the out dict now that it can call for the type of the dict, and assign type to dict

如果您的列表变大,则效率稍低,但这是一个解决方案。

c btw的输出。是:

{'sedan': {'length': 1322, 'width': 850, 'high': 620, 'type': 'sedan', 'e': 55, 'f': 44}, 'truck': {'length': 1400, 'width': 922, 'high': 650, 'type': 'truck', 'e': 85, 'f': 50}}

我还可以自由地将变量转换为字符串。假设您忘了戴上:)

答案 1 :(得分:0)

首先我们制作键/值对,然后将它们变成字典。然后,您可以使用这些字典的type条目将其放入嵌套字典中

def pairs(seq):
    it = iter(seq)
    return zip(it, it)

mylist=[['length', 1322, 'width', 850, 'high', 620, 'type', 'sedan', 'e', 55, 'f', 44], ['length', 1400, 'width', 922, 'high', 650, 'type', 'truck', 'e', 85, 'f', 50]]

dicts = map(dict, map(pairs, mylist))

result = {d['type']: d for d in dicts}

print(result)
# {'sedan': {'length': 1322, 'width': 850, 'high': 620, 'type': 'sedan', 'e': 55, 'f': 44}, 'truck': {'length': 1400, 'width': 922, 'high': 650, 'type': 'truck', 'e': 85, 'f': 50}}