Matt Hines.
Software Engineering Student.
London.
This blog is mainly to display my different projects, as well as a place for me to share and discuss technology news.
Associative arrays in PHP, Hashmaps in Java and Dictionaries in Python. All these terms mean a list that has a key and a value. You access the value in the dictionary but sending in its key.
To Initialize that dictionary in python you got to use squiggly braces.
dictionary = {1:”hello”,2:”world”}
This sets up a dictionary with two keys each with its own values. You can access the value of “hello” by using its key “1”. Example:
print dictionary[1]
This statement will print the world “hello”
After this post I will be using comments in the code snippets. A comment is something that is ignored by the compiled and is used for documentation. In python the comment character is the “#”.
print “Hello world” #This prints hello world
This will ignore everything after the # symbol but it serves as a good tool that will help another person understand what that line does. Or it will help yourself if you come back to this code after a couple of months.
Coming back to dictionaries, they are very useful and are fairly easy to use. You should already know how to create a dictionary but inserting and removing are very easy as well. Example:
dictionary[3] = “New value” #This adds the key “3” with its value “New value”
To remove a key and value you have to use the keyworld “del”
del dictionary[2] #removes the key “2” and its value.
You can also get all the keys or all the values in the dictionaries by using “.keys()” and “.values()” respectively. These methods return a list containing either keys or values.
I hope this has taught you something about dictionaries in python. Please don’t hesitate to ask any questions if you need to.
Thanks for reading.