[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': '192.168.1.100',
'mask': '255.255.255.0',
'gateway': '192.168.1.1',
'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():
print(i)

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

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

dict4

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

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

another way to do it:

for key, _ in example.items():
print(key)

dict2

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

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

another way to do it:

for _, value in example.items():
print(value)

dict3

Advertisement

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