I would like the inner for loop to give me one value and goes on to the next iteration for each outer loop. Appreciate your responds.
Currently the result:
- Personal NameJohn
- Personal NamePeter
- Personal Name123456
- ID #John
- ID #Peter
- ID #123456
- Emergency contactJohn
- Emergency contactPeter
- Emergency contact123456
Result should just be:
- ID #123456
- Personal NameJohn
Emergency contactPeter
employees={'ID #','Personal Name','Emergency contact'} excel={'123456', 'John', 'Peter'} for key in employees: for value in excel: print(key + value)
3 Answers 3
Use zip to iterate over two objects at the same time.
note: you are using sets (created using {"set", "values"}) here. Sets have no order, so you should use lists (created using ["list", "values"]) instead.
for key, value in zip(employees, excel):
print(key, value)
3 Comments
{} creates a set instead of a listval = {} creates and empty dictionary, not set. For an empty set, use val = set()You can use zip after changing the type of your input data. Sets order their original content, thus producing incorrect pairings:
employees=['ID #','Personal Name','Emergency contact']
excel=['123456', 'John','Peter']
new_data = [a+b for a, b in zip(employees, excel)]
Output:
['ID #123456', 'Personal NameJohn', 'Emergency contactPeter']
Comments
First of all, use square brackets [] instead of curly brackets {}. Then you could use zip() (see other answers) or use something very basic like this:
for i in range(len(employees)):
print(employees[i], excel[i])