Reputation: 19
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)}
Upvotes: 1
Views: 184
Reputation: 2794
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
Upvotes: 0
Reputation: 129537
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)}
Upvotes: 3
Reputation: 630
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])
Upvotes: 0
Reputation: 46616
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)
Upvotes: 1
Reputation: 799034
>>> 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)}
Upvotes: 0