Dictionaries
Dictionaries are a type of associative array. They are similar to a list in that they can store multiple pieces of data but they way you organise and access the data is different to a list.
A dictionary consists of a collection of key-value pairs. It's probably easiest to explain this with an example:
The following is a dictionary for UK football teams and their stadiums
key | Team | Liverpool | Man Utd | Arsenal | Chelsea | Shrewsbury |
value | Stadium | Anfield | Old Trafford | Emirates | Stamford Bridge | Montgomery Waters Meadow |
Dictionaries allow you to look at the Key, and python will tell you the value so you could look at Arsenal, and it would give you Emirates. If the Key is not there (eg if Arsenal was not in the dictionary) you would get errors. So maybe use Try and Except with these.
To create this in Python:
- football = {"Liverpool" :"Anfield","Man Utd" : "Old Trafford","Arsenal" : "Emirates", "Chelsea" : "Stamford Bridge", "Shrewsbury" : "Montgomery Waters Meadow"}
A few things to draw your attention to:
- Dictionaires use curly brackets { }
- Each Key and Value are written as one item eg: "Liverpool" :"Anfield"
- The Key is first - "Liverpool", then the Value - "Anfield"
- The Key and Value are separated by a colon :
- The various items in the dictionary are separated by a comma ,
To access the values in the Dictionary you use the Dictionary name and key with [ ] :
- print (football["Chelsea"])
- print (football["Shrewsbury"])
The first one would print "Stamford Bridge", the second, "Montgomery Waters Meadow"
The advantage of this approach is you don't need to know an index number like you would for a list, and you don't need to create a loop to check through all the items to find the one you are interested in - you can still use a loop to find the key from a value though (eg, who plays at Anfield..) see trinket for the example
To add to the Dictionary is really easy:
- football ["Man City"] = "Etihad"
- football ["Leeds"] = "Elland Road"
- football ["Wrexham"] = "The Racecourse"
To delete from a Dictionary, you can use del or pop (same as with a list, pop will tell you what it has deleted, del won't)
- del football["Wrexham"]
or
- football.pop("Man City")