Skip to content

Joseph-T-Gordon

A complete log of all recent projects and skills

Menu
  • About me
  • Posts/Projects
  • Resume/Certifications
Menu

Post #47 (Python Programming) – Methods used by dictionaries and list mutability

Posted on June 18, 2023June 26, 2023 by admin

There are two methods I’d like to talk about today, keys(), items(), and values. Dictionaries are not sequential, which essentially means you cannot iterate through them with a for loop. This is where these methods come in, but why tell you when I can show you.

Ex:

Dictionary = {1: “One”, 2: “Two”, 3: “Three”}

for key in Dictionary.keys():

print(word, “->”, Dictionary[key])

Result:

1 -> One

2 -> Two

3 -> Three

As you can see from the above code you can use they keys method to iterate through a list. This method is essentially grabbing all of the keys within the dictionary and treating them like a list. Now onto the items method, this method doesn’t just provide the keys it provides a key-item pair in the form of a tuple.

Ex:

Dictionary = {1: “One”, 2: “Two”, 3: “Three”}

for number, word in Dictionary.items():

print(number, “->”, word)

Result:

1 -> One

2 -> Two

3 -> Three

As you can see with the use of these functions you can iterate through dictionaries just like you can with lists. An important thing to note is that lists are mutable. Meaning you can alter the values within an existing list

Ex:

Dictionary = {1: “One”, 2: “Two”, 3: “Three”}

Dictionary[3] = “Four”

print(Dictionary)

del Dictionary[3]

print(Dictionary)

Result:

{1: “one”, 2: “two”, 3: “Three”}

{1: “One”, 2: “Two”, 3: “Four”}

{1: “One”, 2: “Two”}

Lastly I would like to talk about values method, while the keys method iterates through the given keys of a dictionary the values method iterates through the given values

Ex:

Dictionary = {1: “One”, 2: “Two”, 3: “Three”}

for values in Dictionary.values():

print(values)

Result:

One

Two

Three

Leave a Reply Cancel reply

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

© 2025 Joseph-T-Gordon | Powered by Minimalist Blog WordPress Theme