Define mylist
mylist = list(range(0,8))
print(mylist)
Result = [0, 1, 2, 3, 4, 5, 6, 7]
Dry run to demonstrate the for loop
for num in mylist:
print(num)
Result:
0
1
2
3
4
5
6
Construct mylist2
mylist2 = [] # initializing an empty array
for num in mylist:
mylist2.append(num**2) # this is the rule - generate the square of num
print(mylist2)
Result = [0, 1, 4, 9, 16, 25, 36, 49]
Dictionary
A dictionary is a collection of key-value pairs contained within a set of curly braces. The key represents the field and the value is the value of the data that is entered into the field.
A dictionary can accommodate multiple value entries per field. Therefore, we may interpret the field as a column and values in the field as rows in a data frame. A dictionary can be converted very easily into a data frame.
The JSON format is very similar to the dictionary, which makes it easy to convert into a data frame. Thus, Python makes it convenient for us to use an API for data extraction and convert the data into a data frame.
Example 1: Single Value Entry
Construct a dictionary
my_dict = {'name': 'Nicholas', 'surname':'Sim'}
List the keys
my_dict.keys()
dict_keys(['name', 'surname'])
List the values
my_dict.values()
dict_values(['Nicholas', 'Sim'])
List the values in the field, "name"
my_dict['name']
'Nicholas'
--
Construct a dictionary
my_dict = {'name': ['Nicholas', 'Diego'], 'surname': ['Sim', 'Lopes']}
my_dict['name']
['Nicholas', 'Diego']
Convert the Dictionary into a data frame
import pandas as pd # we will see this in the next seminar
pd.DataFrame(my_dict)
name surname
0 Nicholas Sim
1 Diego Lopes