Maps (aka Associative Arrays)
This page is under construction. Please come back later.
#!/usr/bin/env python3; import Utils # Begin Main dictionary = {} print("dictionary size: " + str(len(dictionary))) print("dictionary is " + ("empty" if not dictionary else "not empty")) dictionary["apple"] = "red" dictionary["banana"] = "yellow" dictionary["cantaloupe"] = "orange" dictionary["dragonfruit"] = "red" dictionary["elderberry"] = "purple" print("dictionary size: " + str(len(dictionary))) print("dictionary is " + ("empty" if not dictionary else "not empty")) print("bananas are " + dictionary["banana"]) x = "dragonfruit" if ((x in dictionary.keys())) : print(x + " are " + dictionary[x]) else : print("Can't find " + x) x = "fig" if ((x in dictionary.keys())) : print(x + " are " + dictionary[x]) else : print("Can't find " + x) x = "elderberry" Utils.mapRemove(dictionary, x) if ((x in dictionary.keys())) : print(x + " are " + dictionary[x]) else : print("Can't find " + x) print(Utils.mapToString(dictionary))
Output
$ python3 Maps1.py
dictionary size: 0
dictionary is empty
dictionary size: 5
dictionary is not empty
bananas are yellow
dragonfruit are red
Can't find fig
Can't find elderberry
{"apple" => "red", "banana" => "yellow", "cantaloupe" => "orange", "dragonfruit" => "red"}
#!/usr/bin/env python3; import Utils # Begin Main planetDiameters = { "Mercury": 4879, "Venus": 12103, "Earth": 12756, "Mars": 6794, "Jupiter": 142985, "Saturn": 120534, "Uranus": 51115, "Neptune": 49534, "Pluto": 2374, "Ceres": 946, "Eris": 2326, "Makemake": 1430 } for planet in planetDiameters.keys() : print(planet + " has a diameter of " + str(planetDiameters[planet]) + " km")
Output
$ python3 Maps2.py
Mercury has a diameter of 4879 km
Venus has a diameter of 12103 km
Earth has a diameter of 12756 km
Mars has a diameter of 6794 km
Jupiter has a diameter of 142985 km
Saturn has a diameter of 120534 km
Uranus has a diameter of 51115 km
Neptune has a diameter of 49534 km
Pluto has a diameter of 2374 km
Ceres has a diameter of 946 km
Eris has a diameter of 2326 km
Makemake has a diameter of 1430 km
Questions
- {{Who's on first?}}
- {{Who's on second?}}
- {{Who's on third?}}
Projects
More ★'s indicate higher difficulty level.
References
- [[Python Language Reference]]
- [[Python Standard Library]]
- [[Python at TutorialsPoint]]