Tag Archives: scripts

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!


#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']}

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 ….

#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

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

#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

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

#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()

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?


#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

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


#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]

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!

HTML Tags Hunting Around Me – P2PU Level #3

This is my level 3 challenge! The requirement of the challenge was to put together descriptive images representing several html tags and then create a post on my blog. I will be honest, it was really cold outside today and I had to be creative enough with what I had around me. The falling snow is my witness!

So, I took an extra step and created what I think should be a good representation of html tag information – using stickies. I really liked the original idea because it helped me remember the concepts behind the tags very well. Too much talk? Me too, let us just see the photos already!

htmltags

That was the first batch of stickies that I used while putting the project together! Now below is the second and last image showing the remaining tags required by the challenge! Enjoy

htmltags2

Obviously, there are more tags in the html universe! For more information on where to find them, please visit World Wide Web Consortium and you can also visit Mozilla Developer Network . You can also get a real learning experience by trying out W3Schools and Codecademy . The list goes on and on! So, the best thing to do is pick one and see if you like it!

Good luck and I hope you enjoyed this post!

NOTE: If you are wondering how I created those stickies, I used HTML5! You can always drop me a line in the comment section so we can talk more about it!