We provide effective and economically affordable online training courses for R and Python, click here for more details and course registration !

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.

For getting more knowledge of Python and a preview of our training course, you can watch Python tutorial videos on our YouTube channel !


0 Comments

Leave a Reply

Avatar placeholder