In the last post I've presented you two of four basic Python collections: lists and sets (and I've mentioned queues, which are not built-in).
Two remaining ones are tuples, immutable containers which can store a few elements and dictionaries, which can store multiple elements indexed by arbitrary values (for instance strings).
Let's get to our examples.
Tuples
# !/usr/bin/python3
def main():
########## TUPLES #######################
mytuple = 1, 2, "Frodo", "Gandalf"
# can also be:
mytuple = (1, 2, "Frodo", "Gandalf")
print(type(mytuple))
# -> <class 'tuple'>
print(mytuple)
# -> (1, 2, 'Frodo')
print(mytuple[0])
# -> 1
# tuples are immutable, we can't do this:
# mytuple[0] = 10
# ('TypeError: 'tuple' object does not support item assignment')
# ...but we can do this
mytuple = (2,"Baggins", 2, "Istari", "Gamgee")
print(mytuple)
# -> (2, 'Baggins', 2, 'Istari', 'Gamgee')
if __name__ == "__main__":
main()
As we can see, we can store various type elements (like numbers and strings) in tuples. They're initialized by listing the elements in () brackets, or without any brackets at all. We can access them by index. But since tuples are immutable, which means they can't be altered after they're created, we can't assign a new value to tuples' elements. If we want to change such tuple, we have to re-initialize it.
Now, let's get to...
Dictionaries
# !/usr/bin/python3
def main():
########## DICTIONARIES #################
# create a dictionary
# types don't have to be consistent
species_dict = { "Frodo": "Hobbit",
"Gandalf": "Wizard",
"Sam": "Hobbit",
"Boromir": "Human",
3.14: "irrational" }
print(species_dict)
# -> {'Frodo': 'Hobbit', 'Gandalf': 'Wizard', 'Sam': 'Hobbit',
# 'Boromir': 'Human', 3.14: 'irrational'}
species_dict["Gandalf"] = "Maia"
print(species_dict)
# -> {'Frodo': 'Hobbit', 'Gandalf': 'Maia', 'Sam': 'Hobbit',
# 'Boromir': 'Human', 3.14: 'irrational'}
del species_dict["Boromir"]
print(species_dict)
# -> {'Frodo': 'Hobbit', 'Gandalf': 'Maia', 'Sam': 'Hobbit',
# 3.14: 'irrational'}
species_dict["Aragorn"] = "Human"
print(species_dict)
# -> {'Frodo': 'Hobbit', 'Gandalf': 'Maia', 'Sam': 'Hobbit',
# 3.14: 'irrational', 'Aragorn': 'Human'}
species_dict.clear()
print(species_dict)
# -> {}
if __name__ == "__main__":
main()
Dictionaries (similar to Maps from Java, or associative arrays in general) allow to access elements indexed by other objects, like string (in fact, they can be any type, a string, a float or event a custom class object; and types of both elements and indices can vary). They're initialized using curly brackets { } like sets, but then go key-value pairs, where value is separated from key with colon : and each pair is separated with coma ,
Dictionaries are mutable (we changed Gandalf's species from Wizard to Maia). They can be cleared (.clear() method).
No comments:
Post a Comment