如何获取以下字典?

时间:2017-01-01 01:03:23

标签: python-3.x dictionary list-comprehension

from __future__ import print_function

你好我有以下带标签的清单:

label=['0','0','1','0','1','2','4','3','3','3','0']

我有相应的元素列表:

elements=['element0', 'element1', 'element2', 'element3', 'element4', 'element5', 'element6', 'element7', 'element8', 'element9', 'element10']

两者都有相同的长度:

print("length label:",len(label),"length elements",len(elements))

输出:

length label: 11 length elements 11

我想构建一个标签为key的字典,以及具有相同标签的所有元素的列表,这将是所需的输出:

dict={'0':['element0', 'element1','element3','element10'],'1':[ 'element2','element4'],'2':['element7'],
      '3':['element7', 'element8', 'element9'],'4':['element6']}

我正在尝试使用“list comprehensions”,如下所示:

dict={}
for i in range(0,len(elements)):
    dict{i}=[#A list with all the elements that has the same label]

但是我想感谢支持实现所需的字典,感谢您的支持,MCVE如下:

from __future__ import print_function

label=['0','0','1','0','1','2','4','3','3','3','0']
elements=['element0', 'element1', 'element2', 'element3', 'element4', 'element5', 'element6', 'element7', 'element8', 'element9', 'element10']

print("length label:",len(label),"length elements",len(elements))
dict={}

2 个答案:

答案 0 :(得分:1)

>>> from collections import defaultdict
>>> mydict = defaultdict(list)
>>> for i,j in zip(label, elements):
...   mydict[i].append(j)

>>> print mydict
defaultdict(<type 'list'>, {'1': ['element2', 'element4'], '0': ['element0', 'element1', 'element3', 'element10'], '3': ['element7', 'element8', 'element9'], '2': ['element5'], '4': ['element6']})

由于您希望对键进行排序:

>>> from collections import OrderedDict
>>> out_dict = OrderedDict()
>>> for keys in sorted(mydict):
...   out_dict[keys] = mydict[keys]

>>> print out_dict
OrderedDict([('0', ['element0', 'element1', 'element3', 'element10']), ('1', ['element2', 'element4']), ('2', ['element5']), ('3', ['element7', 'element8', 'element9']), ('4', ['element6'])])

答案 1 :(得分:1)

你可以这样使用setdefault

>>> result={}
>>> for k,v in zip(label,elements):
...    result.setdefault(k, []).append(v)
... 
>>> result
{'2': ['element5'], '0': ['element0', 'element1', 'element3', 'element10'], '3': ['element7', 'element8', 'element9'], '4': ['element6'], '1': ['element2', 'element4']}