python - weird issue when creating a dictionary -


i having issue creating dictionary. dictionary {booknumbers: list-of-2-tuples}. here, pairs 2-tuple, , path list.

def pairs2dict(pairs, paths):     dic = {}     pair in pairs:         booknumber = getbooknumber(pair)         path = getpath(pair)         if booknumber in dic:             dic[booknumber].append([pair[1], paths[booknumber])         else:             dic[booknumber] = [pair[1], paths[booknumber])      return dic 

this gives me dic fine , good, except first 2-tuple under each book number split up, , 2 separate elements.

the following bit fixes problem, have no idea why i'm having issue in first place. info!

for booknumber in dic:     dic[booknumber][0] = [dic[booknumber][0], dic[booknumber][1]]     dic[booknumber].pop(1) 

you can solve problem getting rid of conditional using defaultdict:

from collections import defaultdict  def pairs2dict(pairs, paths):     dic = defaultdict(list)     pair in pairs:         booknumber = getbooknumber(pair)         path = getpath(pair)         dic[booknumber].append([pair[1], paths[booknumber])     return dic 

Comments

Popular posts from this blog

python - Selenium remoteWebDriver (& SauceLabs) Firefox moseMoveTo action exception -

html - How to custom Bootstrap grid height? -

transpose - Maple isnt executing function but prints function term -