[英]Convert List to dictionary by key
I have list like this myList = [[5, 1], [6, 1], [7, 1], [8, 1], [9, 1], [10, 1]]
and I want to convert it to dict like {1:[5,6,7,8,9,10]}
the key is second argument of inner list.我有这样的列表
myList = [[5, 1], [6, 1], [7, 1], [8, 1], [9, 1], [10, 1]]
我想转换它像{1:[5,6,7,8,9,10]}
这样的 dict 键是内部列表的第二个参数。
I tried below code but it not work.我尝试了下面的代码,但它不起作用。
for i in range(len(myList))
myDic[myList[i][1]] = [myList[i][1]]
myDic[myList[i][1]].append(myList[i][0])
this can easily be done with a defaultdict
:这可以通过
defaultdict
轻松完成:
from collections import defaultdict
ret = defaultdict(list)
myList = [[5, 1], [6, 1], [7, 1], [8, 1], [9, 1], [10, 1]]
for value, key in myList:
ret[key].append(value)
print(ret) # defaultdict(<class 'list'>, {1: [5, 6, 7, 8, 9, 10]})
if you want to avoid defaultdict
,setdefault
helps:如果你想避免
defaultdict
,setdefault
帮助:
ret = {}
myList = [[5, 1], [6, 1], [7, 1], [8, 1], [9, 1], [10, 1]]
for value, key in myList:
ret.setdefault(key, []).append(value)
print(ret)
note that defaultdict
is in the standard library;注意
defaultdict
在标准库中; so if you use a reasonably modern python interpreter (with python 3 you are good anyway) you can use a defaultdict
.因此,如果您使用相当现代的 python 解释器(使用 python 3 无论如何您都很好),您可以使用
defaultdict
。
Declared d
as the dictionary.将
d
声明为字典。 Then append the first value into the dictionary using the second value as a key in 2D list.然后 append 使用第二个值作为二维列表中的键将第一个值放入字典中。
myList = [[5, 1], [6, 1], [7, 1], [8, 1], [9, 1], [10, 1]]
d = {}
for elem in myList:
try:
d[elem[1]].append(elem[0])
except KeyError:
d[elem[1]] = [elem[0]]
print(d)
Use a defaultdict:使用默认字典:
from collections import defaultdict
myDic = defaultdict(list) # values default to empty list
for a, b in myList:
myDic[b].append(a)
myDic = dict(myDic) # get rid of default value
You can do that easily with a defaultdict
:您可以使用
defaultdict
轻松做到这一点:
myList = [[5, 1], [6, 1], [7, 1], [8, 1], [9, 1], [10, 1], [11, 2], [12, 2]]
from collections import defaultdict
out = defaultdict(list)
for val, key in myList:
out[key].append(val)
print(out)
# defaultdict(<class 'list'>, {1: [5, 6, 7, 8, 9, 10], 2: [11, 12]})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.