[英]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应该使用围绕字符串的引号和列表周围的方括号创建:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.