python - creating a dict from 2 given lists -
this working script wrote build dictionary 2 given lists: i-th object in l1 key value located in i-th place of l2.
l1=[1,2,'a','b'] l2=[(22,'aa'),['x'],('3',),('s',3)] d = {} sizel = len(l1) in range(sizel): key = l1[i] val = l2[i] d[key] = val print "output:\n" print "\nl1=",l1 print "l2=",l2 print "dictionary d = ",d i want try in different way: using dict function. therefore, need creat list tuples guess. cant understand how. try:
l1=[1,2,'a','b'] l2=[(22,'aa'),['x'],('3'),('s','3')] l=[] n=len(l1) in range(n): l.append(l1[i],l2[i]) d=dict(l) print d ofcourse error because wrong-using of append function..
would idea how create "tuple list", list can used dict function.
thanks!
you can zip 2 lists element-wise, create dict that
>>> dict(zip(l1,l2)) {1: (22, 'aa'), 2: ['x'], 'a': ('3',), 'b': ('s', 3)}
Comments
Post a Comment