python Put two list Merge into one dict Methods
Don't use built-in functions , Direct use
def Run():
list2 = [1, 2, 3, 4, 5 ];
list3 = ["a", "b", "c", "d","e"];
dict={
};
i=0;
length=len(list2);
while i<length:
'dict[list2[i]]=list3[i]; This method can also '
dit={
list2[i]:list3[i]};
dict.update(dit);
i+=1;
return dict;
if __name__ == '__main__':
print Run();
Use built-in functions zip
1. The two lists have the same length
l1=[1,2,3,4,5,6]
l2=[4,5,6,7,8,9]
print(dict(zip(l1,l2)))
# result : {1: 4, 2: 5, 3: 6, 4: 7, 5: 8, 6: 9}
2. The length of the two lists is inconsistent ( The principle of obedience to the minority )
l1=[1,2,3,4,5,6]
l2=[4,5,6,7,8,9,10,11,12]
# First, let ls2 and ls1 Equal length , And then again zip
l3=l2[0:len(l1)]
#print(l3)
print(dict(zip(l1,l3)))
# result : {1: 4, 2: 5, 3: 6, 4: 7, 5: 8, 6: 9}
To simplify the ;
ls1=[1,2,3,4,5,6,7]
ls2=[4,5,8,9,1]
print(dict(zip(ls1,ls2)))
# result :{1: 4, 2: 5, 3: 8, 4: 9, 5: 1}