forked from bradtraversy/python_sandbox
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdictionaries.py
More file actions
46 lines (34 loc) · 765 Bytes
/
dictionaries.py
File metadata and controls
46 lines (34 loc) · 765 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# A Dictionary is a collection which is unordered, changeable and indexed. No duplicate members.
# Create dict
person = {
'first_name': 'John',
'last_name': 'Doe',
'age': 30
}
# Use constructor
# person2 = dict(first_name='Sara', last_name='Williams')
# Get value
print(person['first_name'])
print(person.get('last_name'))
# Add key/value
person['phone'] = '555-555-5555'
# Get dict keys
print(person.keys())
# Get dict items
print(person.items())
# Copy dict
person2 = person.copy()
person2['city'] = 'Boston'
# Remove item
del(person['age'])
person.pop('phone')
# Clear
person.clear()
# Get length
print(len(person2))
# List of dict
people = [
{'name': 'Martha', 'age': 30},
{'name': 'Kevin', 'age': 25}
]
print(people[1]['name'])