Looping and Unpacking with Dictionaries and Tuples

Looping and Unpacking with Dictionaries and Tuples

Looping through a Dictionary:

employees = {'mike': 27000, 'john':65000, 'rebeca':6000, 'tom':10000 }

# By default the below for loop is `employees.keys()`
for person in employees:
	print(person) # This will print the KEY of the DICT

for entry in employees.items():
	print(entry)  # This will print the ENTIRE Entry
	
for salary in employees.values():
	print(salary) # This will print the VALUES of the DICT

Unpacking the data:

  • The ability to extract each individual item from a DICT

employees = {'mike': 27000, 'john':65000, 'rebeca':6000, 'tom':10000 }

# By using both the 'key' and the 'value' of the DICT
for key, value in employees.items():
# We can now print the key and value individually:
	print(key)
	print(value)

Unpacking a list of tuples:

employees = [('mike', 27000, 29), ('john',65000, 29), ('rebeca',6000, 29)('tom',10000, 29)]

for (name, salary, age) in employees:
	print(name)
	print(salary)

Last updated