[python] Iterate a dictionary

The list data type is easy to iterate by using for item in items where item is the object in the list - items.

Suppose to iterate through datas within a dictionary, using this as the dictionary:

example = {
'object_name': 'linux',
'address': '',
'mask': '',
'gateway': '',
'prefix': '24'

Returns both the keys and values
Use the for loop to iterate and get the keys and values of the dictionary, and the return value is a tuple.

# returns tuple, example.items return both the keys and values.
for i in example.items():

Another way to do it, the return will not be a tuple:

for key, value in example.items():
print(key + " " + value)


Returns only the keys
Use the for loop to enumerate only the keys.

# return only keys.
for i in example.keys():

another way to do it:

for key, _ in example.items():


Returns only the values
Iterate over the dictionary and returns only values.

# return only values.
for i in example.values():

another way to do it:

for _, value in example.items():



Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s