Python language basics 55: items and values in a dictionary


In the previous post we saw how to copy a set. Both the copy function and the set constructor create shallow copies with all its consequences.

In this post we’ll discuss how to retrieve and iterate over the keys and values of a dictionary.

Looping through a dictionary

We’ve already seen how to loop through a dictionary with a for-each loop in this post. Here’s a reminder:

sizes = {"S": "Small", "M": "Medium", "L": "Large", "XL": "X-Large"}

Here’s how we can print the key and value of each element in a for-loop:

for size in sizes:
    print("Key ", size, ", value: ", sizes[size])

…which prints the following:

Key L , value: Large
Key S , value: Small
Key M , value: Medium
Key XL , value: X-Large

However, there are other key and value related functions available for a dictionary.

Keys only

You can get hold of the keys only using the keys function:

for key in sizes.keys():


Note that there’s no predefined sort order for the items in the dictionary. If you test the above code you may very well see a different key order.

Values only

There’s an equivalent function to retrieve the values in the dictionary:

for val in sizes.values():


Values and items

Finally there’s the items function which returns the key-value pairs in a tuple:

for item in sizes.items():

(‘M’, ‘Medium’)
(‘L’, ‘Large’)
(‘S’, ‘Small’)
(‘XL’, ‘X-Large’)

The elements in the tuple can be assigned to comma-delimited variables for convenient access:

for key, value in sizes.items():
    print("Key: {0}, value: {1}".format(key, value))

Key: L, value: Large
Key: S, value: Small
Key: M, value: Medium
Key: XL, value: X-Large

In the next post we’ll see how to update a dictionary.

Read all Python-related posts on this blog here.

About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

Leave a Reply

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

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

Twitter picture

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

Facebook photo

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

Connecting to %s

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog


Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.

%d bloggers like this: