03-Dictionaries
1. Overview
- Dictionaries provide a mechanism for storing data labelled with a keyword or other information.
- Use curly brackets to create a dictionary, and associate each piece of data with a label.
Shell
>>> a = {'mass': 17.3, 'length': 0.7}
>>> print(a)
{'mass': 17.3, 'length': 0.7}
>>> type(a)
<class 'dict'>Or another syntax
Shell
>>> b = dict(name='Trung', age=38)
>>> print(b)
{'name': 'Trung', 'age': 38}
>>> type(b)
<class 'dict'>2. Some methods particular to dictionaries
a.keys()a.values()a.items()
Shell
>>> a = dict(name='Trung', age=38, hair='black')
>>> print(a)
{'name': 'Trung', 'age': 38, 'hair': 'black'}
>>> a.keys()
dict_keys(['name', 'age', 'hair'])
>>> a.values()
dict_values(['Trung', 38, 'black'])
>>> a.items()
dict_items([('name', 'Trung'), ('age', 38), ('hair', 'black')])
>>>
>>> len(a)
3
>>> a['eyes']='black'
>>> len(a)
4
>>> print(a)
{'name': 'Trung', 'age': 38, 'hair': 'black', 'eyes': 'black'}
>>> print(a.pop('eyes'))
black