thitems()
function doesn't return key/value pairs in any specific order.
my_dict = {
'Name':'Jiayi',
'Age':20,
'height':155
}
print my_dict.items()
[( 'Age', 20), ( 'Name', 'Jiayi' ), ( 'height' , 155) ]
Thekeys()
function returns an array of the dictionary's keys, and
Thevalues()
function returns an array of the dictionary's values.
my_dict = {
'Name':'Jiayi',
'Age':20,
'height':155
}
print my_dict.keys()
print my_dict.values()
['Name', 'Age', 'height' ]
['Jiayi', 20, 155 ]
You can usein
veryin
tuitively, like so:
my_dict = {
'Name':'Jiayi',
'Age':20,
'height':155
}
for key in my_dict:
print key, my_dict[key]
Age 20
Name Jiayi
height 155
for letter in 'JIAYI':
print letter
J
I
A
Y
I
Building Lists
evens_to_50 = [i for i in range(51) if i % 2 == 0]
print evens_to_50
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50]
even_squares = [y**2 for y in range(1,11) if (y**2) % 2 == 0]
print y
[4, 16, 36, 64, 100]
[start:end:stride]
Wherestart
describes where the slice starts (inclusive),end
is where it ends (exclusive), andstride
describes the space between items in the sliced list. For example, a stride of2
would select every other item from the original list to place in the sliced list.
l = [i ** 2 for i in range(1, 11)]
# Should be [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
print l[2:9:2]
[9, 25, 49, 81]
The default starting index is0
The default ending index is the end of the list
The default stride is1
to_five = ['A', 'B', 'C','D','E']
print to_five[3:]
# prints ['D', 'E']
print to_five[:2]
# prints ['A', 'B']
print to_five[::2]
# print ['A', 'C', 'E']
my_list = range(1, 11) # List of numbers 1 - 10
print my_list[0::]
print my_list[::2]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[1, 3, 5, 7, 9]
my_list = range(1, 11)
backwards = my_list[::-1]
print backwards
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]