pingwin850 pingwin850 - 3 months ago 9
Python Question

Join two lists into one dictionary

These are my lists (both lists have the same length - 43 indices):

list1 = [u'UMTS', u'UMTS', u'UMTS', u'GSM', u'GSM', u'GSM', u'GSM', u'GSM', u'GSM', u'GSM', u'GSM', u'GSM', u'GSM', u'GSM', u'GSM', u'GSM', u'GSM', u'GSM', u'GSM', u'GSM', u'GSM', u'GSM', u'GSM', u'GSM', u'GSM', u'GSM', u'GSM', u'GSM', u'GSM', u'GSM', u'GSM', u'GSM', u'GSM', u'GSM', u'GSM', u'GSM', u'GSM', u'GSM', u'GSM', u'GSM', u'GSM', u'GSM', u'LTE']

list2 = [u'60000', u'60000', u'60000', u'118629', u'118629', u'118629', u'118629', u'118629', u'118629', u'118629', u'118629', u'118629', u'118629', u'118629', u'118629', u'120000', u'120000', u'120000', u'120512', u'120512', u'120512', u'120512', u'120512', u'120512', u'118629', u'118629', u'118629', u'120000', u'120000', u'120000', u'118629', u'118629', u'118629', u'118629', u'118629', u'118629', u'118629', u'118629', u'118629', u'118629', u'118629', u'118629', u'300000']


I would like to join them into one dictionary:

dictionary = {
'UMTS' : 'indices from 0 to 2'
'GSM' : 'indices from 3 to 42'
'LTE' : 'index 43'
}


Does anyone know how to do it? Is it possible at all? Thanks in advance !!!

Answer

You can use collections.defaultdict() and zip() function:

>>> from collections import defaultdict
>>> 
>>> d = defaultdict(list)
>>> 
>>> for i, j in zip(list1, list2):
...     d[i].append(j)
... 
>>> d
defaultdict(<type 'list'>, {u'UMTS': [u'60000', u'60000', u'60000'], u'GSM': [u'118629', u'118629', u'118629', u'118629', u'118629', u'118629', u'118629', u'118629', u'118629', u'118629', u'118629', u'118629', u'120000', u'120000', u'120000', u'120512', u'120512', u'120512', u'120512', u'120512', u'120512', u'118629', u'118629', u'118629', u'120000', u'120000', u'120000', u'118629', u'118629', u'118629', u'118629', u'118629', u'118629', u'118629', u'118629', u'118629', u'118629', u'118629', u'118629'], u'LTE': [u'300000']})