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