DEV Community

EvanRPavone
EvanRPavone

Posted on

Learning Python - Week 1

Python… an easy to code, widely used, high-level programming language. I decided to dive into it this week by doing a certification prep course from Udemy. Even though I just started, I am having a lot of fun with it. I am just learning the basics like, variables, data types, basic arithmetic, indexing and slicing strings and a lot more. Next week I will be learning about functions, variable scope and the object oriented side of things. I want to take you on a journey through my python learning experience. What I will be doing is talking about one thing that really stood out to me this week, dictionaries.

Dictionaries have key value pairs and are not position oriented like lists and tuples, they are key oriented. The format for a dictionary would be variable = {‘key’: ‘value}. It reminds me of a JSON API page if you have it filled with information. It’s also, from what I can see, very easy to understand and read. It keeps information organized. You can add lists and tuples inside a dictionary too. Here is an example of a dictionary from the course I am taking:

my_list = [{'Tom': {"salary": 22000, "age": 22, "owns": ['jacket', 'car', 'TV']}},
                {“Mike”: {"salary": 24000, "age": 27, "owns": ["bike", 'laptop', 'boat']}}]
Enter fullscreen mode Exit fullscreen mode

So let’s say that you need to access Mike’s age and show what he owns. Since my_list is a list with a dictionary inside of it you have to give the index of Mike’s dictionary. To do this you can say:

Mike_age = my_list[1][“Mike”][“age”]
Mike_owns = my_list[1][“Mike”][“owns”]
print(mike_age)
print(mike_owns)

# -> mike_age returns 27
# -> mike_owns returns a list of [“bike”, “laptop”, “boat”]
Enter fullscreen mode Exit fullscreen mode

You wouldn’t use an index to get mikes information, you would use the key like “Mike” which will return the value {"salary": 24000, "age": 27, "owns": ["bike", 'laptop', 'boat']}. I used an index because Mike is the second index ([1]) of the list that Tom and Mike are in. Let’s say you now want to remove Mike, this is where the pop() method comes in. The pop() method can remove a key and its values but it can also grab the the key and its values if you set a variable to it like so:

mike = my_list[1]
# In a list so you have to say which index mike is in [1]
mike_info = mike.pop(“Mike”)
print(my_list) 
# This will just return Tom and his information
print(mike_info)
# This will return mikes info
Enter fullscreen mode Exit fullscreen mode

This was a very fun thing to do this week for my learning experience with Python. You can access everything I learned on my Github. I think I will enjoy Python a lot. I know I haven’t gotten far into it but we shall see!

Top comments (0)