DS4UX (Spring 2016)/Day 3 lecture: Difference between revisions

From CommunityData
Line 215: Line 215:
  >>> your_dict.get("Alice")
  >>> your_dict.get("Alice")
  'chocolate'
  'chocolate'
==== Dictionary keys can be integers, and their values can be any data type ====
>>> mixed_dict = {1:3, 2:'two', 3:False, 'four':['john','terry','graham']}
>>> print(mixed_dict[1])
3
>>> print(mixed_dict[2])
two
>>> print(mixed_dict[3])
False
>>> print(mixed_dict['four'][2])
graham


====Changing elements of a dictionary====
====Changing elements of a dictionary====

Revision as of 18:02, 11 April 2016

Review of some important Week 2 concepts

Lists

  • Use lists to store data where order matters.
  • Lists are indexed starting with 0.

List initialization

>>> my_list = []
>>> my_list
[]
>>> your_list = ["a", "b", "c", 1, 2, 3]
>>> your_list
['a', 'b', 'c', 1, 2, 3]

Access and adding elements to a list

>>> len(my_list)
0
>>> my_list[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range
>>> my_list.append("Alice")
>>> my_list
['Alice']
>>> len(my_list)
1
>>> my_list[0]
'Alice'
>>> my_list.insert(0, "Amy")
>>> my_list
['Amy', 'Alice']
>>> my_list = ['Amy', 'Alice']
>>> 'Amy' in my_list
True
>>> 'Bob' in my_list
False

Changing elements in a list

>>> your_list = []
>>> your_list.append("apples")
>>> your_list[0]
'apples'
>>> your_list[0] = "bananas"
>>> your_list
['bananas']

Slicing lists

>>> her_list = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
>>> her_list[0]
'a'
>>> her_list[0:3]
['a', 'b', 'c']
>>> her_list[:3]
['a', 'b', 'c']
>>> her_list[-1]
'h'
>>> her_list[5:]
['f', 'g', 'h']
>>> her_list[:]
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']

sorting lists

Use .sort() to sort a list:

>>> names = ["Eliza", "Joe", "Henry", "Harriet", "Wanda", "Pat"]
>>> names.sort()
>>> names
['Eliza', 'Harriet', 'Henry', 'Joe', 'Pat', 'Wanda']

Getting the maximum and minimum values from a list

>>> numbers = [0, 3, 10, -1]
>>> max(numbers)
10
>>> min(numbers)
-1

Strings

Strings are a lot like lists
>>> my_string = "Hello World"
>>> my_string[0]
'H'
>>> my_string[:5]
'Hello'
>>> my_string[6:]
'World'
>>> my_string = my_string[:6] + "Jessica"
>>> my_string
'Hello Jessica'
>>> 'H' in my_string
True
String formatting
>>> x = 1
>>> y = 1.234
>>> z = True
>>> w = "elevator"
>>> all_together_now = "You can put ints like %d, floating point numbers like %f, boolean values like %s, and other strings like %s into a string without changing them to strings first!" % (x,y,z,w)

New concepts for Week 3 exercises and challenges

Generating a list of numbers easily with range()

>>> range(5)
[0, 1, 2, 3, 4]
>>> for i in range(5):
...     print "Hi" * i
...

Hi
HiHi
HiHiHi
HiHiHiHi

The range() function returns a list of numbers. This is handy for when you want to generate a list of numbers on the fly instead of creating the list yourself.

>>> range(5)
[0, 1, 2, 3, 4]

Use range when you want to loop over a bunch of numbers in a list, or perform an operation a certain number of times:

>>> numbers = range(5)
>>> for number in numbers:
...     print(number * number)
...
0
1
4
9
16

We could rewrite the above example like this:

>>> for number in range(5):
...     print(number * number)
...
0
1
4
9
16

Get user input with input()

>>> for i in range(100):
...     my_input = input("Please type something> ")
...     if input == "Quit":
...         print("Goodbye!")
...         break
...     else:
...         print("You said: " + my_input)
... 
Please type something> Hello
You said: Hello
Please type something> How are you?
You said: How are you?
Please type something> Quit
Goodbye!
>>>

Dictionaries

  • Use dictionaries to store key/value pairs.
  • Dictionaries do not guarantee ordering.
  • A given key can only have one value, but multiple keys can have the same value.

Initialization

>>> my_dict = {}
>>> my_dict
{}
>>> your_dict = {"Alice" : "chocolate", "Bob" : "strawberry", "Cara" : "mint chip"}
>>> your_dict
{'Bob': 'strawberry', 'Cara': 'mint chip', 'Alice': 'chocolate'}

Types

>>> type(my_dict)
<type 'dict'>

Adding elements to a dictionary

>>> your_dict["Dora"] = "vanilla"
>>> your_dict
{'Bob': 'strawberry', 'Cara': 'mint chip', 'Dora': 'vanilla', 'Alice': 'chocolate'}

Accessing elements of a dictionary

>>> your_dict["Alice"]
'chocolate'
>>> your_dict.get("Alice")
'chocolate'
>>> your_dict["Eve"]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'Eve'
>>> "Eve" in your_dict
False
>>> "Alice" in your_dict
True
>>> your_dict.get("Eve")
>>> person = your_dict.get("Eve")
>>> print(person)
None
>>> print(type(person))
<type 'NoneType'>
>>> your_dict.get("Alice")
'chocolate'

Dictionary keys can be integers, and their values can be any data type

>>> mixed_dict = {1:3, 2:'two', 3:False, 'four':['john','terry','graham']}
>>> print(mixed_dict[1])
3
>>> print(mixed_dict[2])
two
>>> print(mixed_dict[3])
False
>>> print(mixed_dict['four'][2])
graham

Changing elements of a dictionary

>>> your_dict["Alice"] = "coconut"
>>> your_dict
{'Bob': 'strawberry', 'Cara': 'mint chip', 'Dora': 'vanilla', 'Alice': 'coconut'}

Looping through a dictionary

>>>for i in your_dict.items():
>>>    print(i)
('Bob', 'strawberry')
('Cara', 'mint chip')
('Dora', 'vanilla')
('Alice', 'chocolate')
>>>for i_key in your_dict.keys():
>>>    print(i_key + " is a key in this dictionary")
Bob is a key in this dictionary
Cara is a key in this dictionary
Dora is a key in this dictionary
Alice is a key in this dictionary
>>>for i_val in your_dict.values():
>>>    print(i_val + " is a value in this dictionary")
strawberry is a value in this dictionary
mint chip is a value in this dictionary
vanilla is a value in this dictionary
chocolate is a value in this dictionary
>>> for i_key, i_val in your_dict.items():
>>>     print(i_key + " is the key for " + i_val)
>>>     print(i_val + " is the value for " + i_key)
>>>     print("\n")
Bob is the key for strawberry
strawberry is the value for Bob
...
Cara is the key for mint chip
mint chip is the value for Cara
...
Dora is the key for vanilla
vanilla is the value for Dora
...
Alice is the key for chocolate
chocolate is the value for Alice
  • dict keys can be integers

Exercise

Click here to download the scripts for this week's in-class exercise