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 Course Source Files !
For online Python training registration, click here ! Pandas provides flexible ways of generating data…
For online Python training registration, click here ! Data frame is the tabular data object…
Click her for course registration ! When a data frame in Python is created via…
We provide affordable online training course(via ZOOM meeting) for Python and R programming at fundamental…