Geek Logbook

Tech sea log book

Dictionary methods: keys(), values(), and items()

In Python, there are three special methods related to dictionaries that are worth mentioning: keys(), values(), and items(). Interestingly, these methods do not return true lists. They cannot be modified and do not have an append() method. However, dict_keys, dict_values, and dict_items can be used in for loops. This distinction is important to keep in mind.

david={'hair':'brown','age':42}

print(david)            # {'hair': 'brown', 'age': 42}
values = david.values() #dict_values(['brown', 42])
keys = david.keys()     #dict_keys(['hair', 'age'])
items = david.items()   #dict_items([('hair', 'brown'), ('age', 42)])

#Print the values of the dictionary
print("Values: ", values)
for v in values:
    print(v)

#Print the keys of the dictionary
print("Keys: ", keys)
for k in keys:
    print(k)

#Print the items of the dictionary
print("Items: ", items)
for i in items:
    print(i)

If we want to convert what this method returned into a list we can us the list method.

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *.