Dictionary objects in Python make storing key-value pairs information fairly easy and straightforward. The information of the dictionary can be returned by using a for loop. There are usually three type of for loops mentioned with respect to the dictionary’s attributes: ‘items’ for getting key-value pairs, ‘keys’ for returning all the keys and ‘values’ for getting all the values. Following code examples show these three cases.
#create a dictionary
familymember_0 = {'firstname': 'Wei',
'lastname': 'Zhang',
'age': '32',
}
#1. looping through items, return all the key value pairs information
for key, value in familymember_0.items():
print("\nKey: " + key)
print("Value: " + value)
#output
Key: firstname
Value: Wei
Key: lastname
Value: Zhang
Key: age
Value: 32
#2. looping through keys
for name in familymember_0.keys():
print(name.title())
#output
Firstname
Lastname
Age
#3. Looping through all the values
for value in familymember_0.values():
print(value)
#output
Wei
Zhang
32
Just note, the temporary variable in each of the for loops listed above can use any allowed name.
Click here to download Python Machine Learning Source Files !
PyTorch is a deep learning package for machine learning, or deep learning in particular for…
Topic modeling is a subcategory of unsupervised machine learning method, and a clustering task in…
For online Python training registration, click here ! Sentiment classification is a type of machine…
Click here to download Python Course Source Files !