I generate a dictionary from 2 list first list is key and second is value, if value in dictionary is None I must write 'None' to the key. Length of lists can be different.
def all_list(l1, l2):
d = {}
for k, v in zip(l1, l2):
if v in d is None:
d[k] = 'none'
d[k] = v
return d
r1 = ['1',2,3,5,6,7]
r2 = ('andrey','kapar','isa','murat')
print all_list(r1, r2)
{'1': 'andrey', 2: 'kapar', 3: 'isa', 5: 'murat'}
{'1': 'andrey', 2: 'kapar', 3: 'isa', 5: 'murat', 6:'None', 7: 'None'}
Check how zip is working:
>>> r1 = ['1',2,3,5,6,7]
>>> r2 = ('andrey','kapar','isa','murat')
>>> zip(r1,r2)
[('1', 'andrey'), (2, 'kapar'), (3, 'isa'), (5, 'murat')]
Python's zip will not add None's if the lengths are not compatible Your easiest option would be to make r2 a list and do the following in all_list before your for loop
for i in range(len(l1), len(l2)):
l1.append(None)
for i in range(len(l2), len(l1)):
l2.append(None)
Simple and stupid solution
for i in xrange(len(r1)):
try:
d[r1[i]] = r2[i]
except IndexError:
d[r1[i]] = 'None'
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.