Thursday, 15 September 2011

Dictionaries

Creating a dictionary in Python


It's easier than you (I) would think!
And it has humoured me this morning. Really tickled my script-buds.


I created a dictionary called 'student'. Within the dictionary we assigned different values (see below for mine). You can then make queries within the dictionary to find if something exists in there or not.


I asked if we had any creative license with this, we were granted a small amount of creative license and I rolled with it like a stone gathering a shed-load of moss.


student = {'alcohol': '60%','facility_to_learn': '15%', 'tolerance': '5%', 'culinary_skills': '4%', 'project_management': '7%', 'arithmatic_skills': '10%'}


You can add extra values later by using this:


student['enthusiasm'] = '6.5%'


To query the dictionary you need to type something like:


'alcohol' in student


And it returns a Boolean (Bool) value (True or False).



>>> 'alcohol' in student
True


After multiple attempts I had created this.





Although this was humorous I then learnt that '4%' is not a numeric value, but a string. A string is literally a group of characters, not a number (or a percentage as I wanted). This meant you could not query whether this student had an alcohol rating of above 50% (student['alcohol']  > '50%').


Instead I had to rewrite my dictionary to get rid of my '%'s, which rendered my 'arithmatic_skills': '10%' not funny (add up original values as %'s to see the funny side). Bad Time Bear had come out to play :/ 
Having said that I managed to complete the task at hand.







However this can be hugely helpful when searching through databases and returning values of unknown quantities ie. you can return all the ' 'student IDs' > 000100 ' or all students whose ' course == Digital_Journalism ' etc.





I can't help but feel like I've created the geekiest form of top trumps ever but you can then add more students to your dictionary.
Firstly, you create new students with the same items and values (if each has an enthusiasm value it's easier to search).













Then you create a name for your database, in this case 'students' and include all the names of your dictionaries.


You can [import, then] use pprint to display the list of items in a much easier to read manner (pprint.pprint(lab)).










I also learnt that 6 > a . Profound.

No comments:

Post a Comment