Hone Your Powers – Programming 101

In this challenge, we are required to learn some basic python or ruby constructs that could be useful while converting data returned by Twitter API calls into useful information that we can use in applications. Of course we don’t have to use either of those languages. There are other great languages like Javascript and PHP that you could give a shot! Either way, let us start this ball rolling: I am going with Python!

[python]

#make a simple dictionary/hash, add some items to it
#experiment on retrieving them by key and by value
#dictionaries are mutable

#dictionary #1
book = {‘title’:’My Life Sentences’, ‘year’:2013,
‘author’:’Elisha Chirchir’, ‘genre’:’Non-Fiction’}

#dictionary #2
john = {‘gender’:’Male’, ‘profession’:’Engineer’, ‘age’:25,
‘friends’:[‘jack’,’kim’, ‘walter’, ‘jane’]}
[/python]

I just created two dictionaries! How can you identify a dictionary(sometimes called hash tables) in python? The answer is simple: look for the curly braces ({}). You might have noticed in the second dictionary that you can have other data types inside the dictionary and even another dictionary! Next ….

[python]
#add items, retrieve items, by key and by value:
#example 1: add price to book.
#example 2: add country to john

book[‘price’] = 2.99 #this adds price(key) with 2.99(value)
john[‘country’] = ‘USA’ #this adds country(key) with USA(value)

#Retrieve data using keys
book[‘title’] #this will return: ‘My Life Sentences’
book[‘genre’] #this will return: ‘Non-Fiction’
john[‘profession’] #this will return: ‘Engineer’
john[‘friends’] #this will return a list of friends shown
book.get(‘price’) #get() method return: 2.99
john.get(‘country’) #get() method return: ‘USA’

#Grab all keys or all values:
book.keys() #returns: title, year, author, genre, price
john.keys() #returns: gender, profession, age, friends
book.values() #returns: My Life Sentences, 2013,
#Elisha Chirchir, Non-Fiction, 2.99
john.values() #Male, Engineer, 25,
#[‘jack’, ‘kim’, ‘walter’, ‘jane’], USA

[/python]

There are other methods associated with dictionaries. If you don’t need something in your dictionary anymore, you … delete it!

[python]
#to delete a key:value from a dict:
del book[‘price’] #this removes price(key) and 2.99(value)
del john[‘friends’] #remove all friends – new year’s resolution

[/python]

Next, let us check out the other commonly used construct: List

[python]
#create some lists and populate them with data
#a list can contain other lists, and different data types
first_list = [1, 10, [‘one’, ‘two’, True, 100], [‘another’]]
second_list = [None, [‘Hello’, ‘world’, ‘Mozilla’, 1], [0, [12,
3, 100,’something’]]]

#access data in the list using the index!
first_list[0] #returns 1 — at index 0
first_list[3] #returns [‘another’] — at index 3

second_list[0] #returns nothing [NONE]
second_list[1] #returns [‘one’, ‘two’, True, 100]
second_list[2][0] #returns 0
second_list[2][1][3] # returns ‘something’

#delete items from the list using del – just like in dictionary
del first_list[1] #this removes 10 from first list
del second_list[2][0] #this removes 0 from second list

#add new items to the list and sort the lists.
first_list[2] = “newthing” #adds ‘newthing’ to position 2
second_list[0] = “some other thing” #adds this to index 0

first_list.sort() #this sorts the list : check sorted()
second_list.reverse() #this reverses the list : check reversed()
[/python]

There are several other methods you can use to manipulate list items and I will leave that to you as an assignment! Now to the next part: Difference between retrieving data from a dictionary and from a list:

In both cases, you can use the del method to remove items. To retrieve data from a dictionary, you use the key –dict[key] but to do the same from a list, you use index notation –list[index] starting from 0. A dictionary has a get() method but a list doesn’t. You can also access their data using a for…in loop as we shall see soon! Back to code right?

[python]

#write an if statement to check for a value in a list
my_list = [‘schools’, ‘karma’, 2013, ‘usa’, ‘africa’, True]
if ‘karma’ in my_list:
return ‘karma’ + ‘ located’ #returns karma located
#also,
if ‘hello’ in my_list:#this returns False

return ‘True’

else:

       return False
#—————————————#
#write an if statement to check for a key in a dictionary and
#return its value!
dict = {‘name’:’John Kerry’, ‘profession’:’Politician’, ‘age’:50}
if ‘name’ in dict:
return dict[‘name’] #returns value associated with ‘name’

#also,
if ‘name’ not in dict:
return ‘Not found!’ #you could add a new key:value here
else:
return dict[‘name’] #return it because it was found
[/python]

Lastly, let us enumerate through our dictionary and print out the key:value pairs! Make it look awesome!

[python]

#create a dictionary, add some items to it and then use a
#for loop to print them out in a pretty manner: key:value format
last_dict = {‘color’:’blue’, ‘age’:20, ‘fav_food’:’corn’,
‘profession’:’Teacher’}

#now let us use a for loop.
for key in last_dict:
print key, “:”, last_dict[key] #prints out neatly

#—————outcome: —————–#
# color: blue
# age: 20
# fav_food: corn
# profession: Teacher

#this is just an extra bonus: How to use an if statement
#inside a for loop.

for key in last_dict:
if last_dict[key] == 20:
del last_dict[key] #remove your age, it is 2013
else: #otherwise print the rest!
print key, “:”, last_dict[key]
[/python]

Thanks for visiting and reading through this tutorial. I really hope you learned something like I did. The truth is that this is just the tip of the iceberg. There is a lot to be learned as far as Python is concerned. Find more information by visiting python.org where it all started! If you have any questions, please do not hesitate to ask me. Good luck!

Be The First To Get New Posts From Simple Developer…

Written By Elisha Chirchir

Elisha Chirchir is a software developer. He is also the founder of Simple Developer and co-founder of Instinctive Software Solutions. On any given day, he works on both Android and Web Development. During his 'free time', he offers training to those interested in learning how to code in php, java, python, javaScript etc. You can easily find him on StackOverflow Android chatroom or on Twitter @Eenvincible

Leave a Reply

Your email address will not be published. Required fields are marked *