This program builds a dictionary out of a list based on what two index numbers you would like from the list.
this is the output
{‘a’: 2, ‘c’: 7, ‘b’: ‘h’}
def buildDict2(theList,inputOne,inputTwo) :
newdict={}
for a in theList:
if inputTwo >= len(a):
print "error"
return "error"
if inputOne >= len(a):
print "error"
return "error"
for oneValue in a:
print len(a)
varkey=a[inputOne]
varvalue=a[inputTwo]
newdict[varkey]=varvalue
return newdict
print buildDict2([["a", "s","d", 2,0,1],["b", "f",3,"h",0,2],["c", "g",5,7]],0,3)
How do i convert this to a single loop?
+1 all answers
thank you for your help, it is greatly appreciated.
basically i just need to use one loop instead of two
edit: important concept: it takes a dictionary and two numbers. the two numbers tell the program what index of the lists to use. list=[[a,b,c],[d,e,f],[h,g,i]] used with the numbers 0 and 2 will return a dictionary with three entries. the keys will be the first input. so the keys are a d and h, and the values are going to be the list index of second input, so c, e i. get it?
for this code
def buildDict2(theList, range1, range2, newdict = {}):
for a in theList:
if range2 >= len(a) or range1 >= len(a):
return "error"
newdict[a[range1]] = a[range2]
return newdict
print buildDict2([["a", "s","d", 2,0,1],["b", "f",3,"h",0,2],["c", "g",5,7]],0,3)
i am getting {‘a’: 2}
when i want to get
{‘a’: 2, ‘c’: 7, ‘b’: ‘h’}
whats the problem?
changed to pep8 indentation as per Jakob’s recommendation so you can see the indentation more clearly. you put your return statement at the wrong level.
corrected mutable default as per astynax’s comment.