简体   繁体   中英

Python list to dict with multiple values for each key

Can the list

mylist = ['a',1,2,'b',3,4,'c',5,6]

be used to create the dict

mydict = {'a':(1,2),'b':(3,4),'c':(5,6)}

You can try something like this:

>>> mylist = ['a',1,2,'b',3,4,'c',5,6]
>>> 
>>> v = iter(mylist)
>>> mydict = {s: (next(v),next(v)) for s in v}
>>> mydict
{'a': (1, 2), 'c': (5, 6), 'b': (3, 4)}

Only if you have some kind of criteria which ones are the keys. If the strings are the keys then:

d = {}
key = None
for item in my_list:
    if isinstance(item, str):
        key = item
    else:
        d.setdefault(key, []).append(item)
>>> dict((x, (y, z)) for (x, y, z) in zip(*[iter(['a',1,2,'b',3,4,'c',5,6])]*3)) 
{'a': (1, 2), 'c': (5, 6), 'b': (3, 4)}
mylist = ['a',1,2,'b',3,4,'c',5,6]

mydict = {}

for i in range(len(mylist))[::3]:

    mydict[mylist[i]] = (mylist[i+1],mylist[i+2])

Yes, but your mydict should be created with quotation marks surrounding strings, and square brackets around your list:

mydict = {"a":[1,2],"b":[3,4],"c":[5,6]}

Otherwise, if you're looking to use that list to programmatically create your dictionary:

mydict = {}
i = 0
while i < len(mylist):
    mydict[mylist[i]] = [mylist[i+1], mylist[i+2]]
    i = i + 3

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