Boston Python Workshop 3/Data types: Difference between revisions

no edit summary
imported>Jesstess
imported>Jesstess
No edit summary
Line 247:
>>> type(my_list)
<type 'list'>
</pre>
 
==Dictionaries==
 
====Initialization====
 
<pre>
>>> my_dict = {}
>>> my_dict
{}
>>> your_dict = {"Alice" : "chocolate", "Bob" : "strawberry", "Cara" : "mint chip"}
>>> your_dict
{'Bob': 'strawberry', 'Cara': 'mint chip', 'Alice': 'chocolate'}
</pre>
 
====Adding elements to a dictionary====
 
<pre>
>>> your_dict["Dora"] = "vanilla"
>>> your_dict
{'Bob': 'strawberry', 'Cara': 'mint chip', 'Dora': 'vanilla', 'Alice': 'chocolate'}
</pre>
 
====Accessing elements of a dictionary====
 
<pre>
>>> your_dict["Alice"]
'chocolate'
>>> your_dict.get("Alice")
'chocolate'
</pre>
 
<pre>
>>> your_dict["Eve"]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'Eve'
>>> "Eve" in her_dict
False
>>> "Alice" in her_dict
True
>>> your_dict.get("Eve")
>>> person = your_dict.get("Eve")
>>> print person
None
>>> print type(person)
<type 'NoneType'>
>>> your_dict.get("Alice")
'coconut'
</pre>
 
====Changing elements of a dictionary====
 
<pre>
>>> your_dict["Alice"] = "coconut"
>>> your_dict
{'Bob': 'strawberry', 'Cara': 'mint chip', 'Dora': 'vanilla', 'Alice': 'coconut'}
</pre>
 
====Types====
 
<pre>
>>> type(my_dict)
<type 'dict'>
</pre>
Anonymous user