Python

How to loop through a dictionary in Python

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 !

wilsonzhang746

Recent Posts

Download R Course source files

Click here to download R Course source files !

2 months ago

Download Python Course source files

Click here to download Python Course Source Files !

2 months ago

How to create a data frame from nested dictionary with Pandas in Python

For online Python training registration, click here ! Pandas provides flexible ways of generating data…

5 months ago

How to delete columns of a data frame in Python

For online Python training registration, click here ! Data frame is the tabular data object…

5 months ago

Using isin() to check membership of a data frame in Python

Click her for course registration ! When a data frame in Python is created via…

5 months ago

How to assign values to Pandas data frame in Python

We provide affordable online training course(via ZOOM meeting) for Python and R programming at fundamental…

5 months ago