1

Here is my code:

x = ['ann', 'D4B3', 'richard', 'A4N5', 'lily', 'M3L1', 'david', 'P4N5', 'bea', 'S3B2']

List = []

i = 0
while i < len(x):
   a = 1
   name_list = 'list' + str(a)
   name_list = {
      'wife_code': x[i+1],
      'wife_list': x[i],
      'husband_code': x[i+3],
      'husband_list': x[i+2],
   }

   List.append(name_list)
   a += 1
   i += 4

print(List)

Upon running the code, it is throwing "IndexError: list index out of range". I know that the error is happening in the 3rd loop because it doesn't have a 'husband_code' and 'husband_list'. Is there a way to print "no value" on that indices that are out of range?

Expected output:

[{'wife_code': 'ann', 'wife_list': 'D4B3', 'husband_code': 'richard', 'husband_list': 'A4N5'}, 
{'wife_code': 'lily', 'wife_list': 'M3L1', 'husband_code': 'david', 'husband_list': 'P4N5'}, 
{'wife_code': 'bea', 'wife_list': 'S3B2', 'husband_code': 'no value', 'husband_list': 'no value'}]
aryastark
  • 25
  • 5

1 Answers1

0

Use itertools.zip_longest with dict

Ex:

from itertools import zip_longest
x = ['ann', 'D4B3', 'richard', 'A4N5', 'lily', 'M3L1', 'david', 'P4N5', 'bea', 'S3B2']
result = []
keys = ['wife_list', 'wife_code', 'husband_list', 'husband_code']
for i in range(0, len(x), 4):
    result.append(dict(zip_longest(keys, x[i:i+4], fillvalue='no value')))

print(result) 

with a list comprehension

Ex:

result = [dict(zip_longest(keys, x[i:i+4], fillvalue='no value')) for i in range(0, len(x), 4)]

Output:

[{'husband_code': 'A4N5',
  'husband_list': 'richard',
  'wife_code': 'D4B3',
  'wife_list': 'ann'},
 {'husband_code': 'P4N5',
  'husband_list': 'david',
  'wife_code': 'M3L1',
  'wife_list': 'lily'},
 {'husband_code': 'no value',
  'husband_list': 'no value',
  'wife_code': 'S3B2',
  'wife_list': 'bea'}]
Rakesh
  • 81,458
  • 17
  • 76
  • 113