The key is unique within each dictionary and identifies the element much as the index identifies each element of a list, string or tuple. The value need not be unique.
Dictionaries are a data type, like tuples and lists, and as such can be assigned to variables, and you can go through them with a for loop. A quick script as an example:
#!/usr/bin/python3
def main():
meals = {'breakfast': 'cereal', 'elevenses': 'tea & digestives', 'lunch':'sausages & pasta', 'teatime': 'Earl Grey & cookies', 'Supper': 'Beef stew & mash'}
for z in meals:
print ('For', z, 'I had', meals[z])
main()
gives the output
RESTART: C:/Users/John/Dropbox/Misc Programming/Python/python3/test08_dicttest.py
For breakfast I had cereal
For elevenses I had tea & digestives
For lunch I had sausages & pasta
For teatime I had Earl Grey & cookies
For Supper I had Beef stew & mash
>>>
So here meals is the variable that refers to the whole dictionary, which in code is enclosed in curly brackets or braces {}, as opposed to square brackets [] for lists and round brackets () for tuples.
There are five elements, not ten, in this particular dictionary - each element consists of a key (here the name of the meal) and the value (what the meal consisted of). I have paired them up using colons between the key and value for each element, and separating each element with a comma. Technically you can use other punctuation to do the same job, but I find this style easy to read.
The print() statement shows firstly that the for loop picks up the key (here z) and to get the corresponding value you use meal[z], which effectively asks Python 'What value does the key z hold in the dictionary meals?'
Here we have been using strings for both keys and values, but other data types can be used for either. This is a longer program that actually uses two user-defined functions:
#!/usr/bin/python3
staffdict = {
'CEO':['Chief Executive Officer', 150000, 'Alice', 'Adams'],
'CFO':['Chief Finance Officer', 120000, 'Bob', 'Banner'],
'CS':['Company Secretary', 70000, 'Charlie', 'Chadwick'],
'CIO':['Chief Information Officer', 90000, 'Donald', 'Davis'],
'SMO':['Senior Marketing Officer', 90000, 'Ellen', 'Edwards'],
'HOP':['Head of Personnel', 90000, 'Fred', 'Farmer']}
def display(post):
print('Abbreviated Post:', post)
print('Full title:', staffdict[post][0])
print('Salary: £', staffdict[post][1])
print('First name:', staffdict[post][2])
print('Last name:', staffdict[post][3])
def main():
print('Omnicorp senior personnel')
stafflist = list(staffdict.keys())
print (stafflist)
print('Please enter post you wish to view (or just enter to quit)')
post = 'x'
while post != '':
post = input('?:')
post = post.upper()
if post in stafflist:
display(post)
elif post == '':
print('Quitting program')
break
else:
print('Sorry, post not recognised')
main()
And the output is:
>>>
RESTART: C:/Users/John/Dropbox/Misc Programming/Python/python3/test08_dicttest2.py
Omnicorp senior personnel
['CEO', 'CFO', 'CS', 'CIO', 'SMO', 'HOP']
Please enter post you wish to view (or just enter to quit)
?:ceo
Abbreviated Post: CEO
Full title: Chief Executive Officer
Salary: £ 150000
First name: Alice
Last name: Adams
?:smo
Abbreviated Post: SMO
Full title: Senior Marketing Officer
Salary: £ 90000
First name: Ellen
Last name: Edwards
?:
Quitting program
>>>
Okay, so the dictionary here is called staffdict, and the keys are strings, and the values are lists (with each index functioning as a column in a table).
Near the start of the main() there is the line
stafflist = list(staffdict.keys())
This creates a list (here called stafflist) of all the keys in the dictionary staffdict. This can be useful, such as for sorting (you cannot sort a dictionary directly, but you can sort a list of its keys).
The main() function is mostly a while loop.
As long as the user enters a valid key (checked by if post in stafflist:), it will call the function display(), with the key (here using the variable post) as the argument. This in turn will look up the value for that key and then present the contents of that value.
No comments:
Post a Comment