繁体   English   中英

嵌套列表到嵌套字典

[英]Nested Lists to a nested dictionary

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

我需要转换我的对象列表:

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}
}

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

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}}

我也冒昧地把你的变量变成了字符串。 假设你忘了把它们放在:)

首先我们创建键/值对,然后我们将它们变成字典。 然后,您可以使用这些词典的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}}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM