简体   繁体   中英

Nested Lists to a nested dictionary

This is my first post and I have some problems with my code.

I need to transform my objects list:

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

Into a dictionary like this:

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

I do not know how to do it... Thanks in Advance!

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

it is slightly ineficient if you list gets bigger but it is a solution.

The output for c btw. is:

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

i also took the liberty to turn your variables in to strings. Assumed you forgot to put them on :)

First we make the key/value pairs, then we turn those into dictionaries. Then you can use the type entry of those dictionaries to put them in the nested dictionary

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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