In [25]:
# create an empty dictionary
d = dict()
# or
d = {}
In [26]:
bob1 = dict(name='Bob', job='dev', age=40)
print bob1
In [27]:
bob2 = dict(zip(['name', 'job', 'age'], ['Bob', 'dev', 40]))
print bob2
In [31]:
bob2['name'] = 'jimmy'
In [32]:
bob2['name']
Out[32]:
In [33]:
bob1['name']
Out[33]:
In [29]:
# create a dictionary
d = {'Name': 'Jimmy',
"phone": '850-882-0340',
"Work": "Eglin AFB",
1:3}
d
Out[29]:
In [81]:
# get the value of 'Name'
d['Name']
Out[81]:
In [45]:
# dictionary keys are case sensitive
d['name']
In [83]:
# get value of a key. it not present give back message
d.get('name', 'no such key')
Out[83]:
In [46]:
# change a value
d['Name'] = 'James'
d
Out[46]:
In [47]:
# add a key-value
d['school'] = 'Aubun'
d
Out[47]:
In [48]:
# rm a key-value
del d['school']
d
Out[48]:
In [49]:
# change it to a string
str(d)
Out[49]:
In [50]:
# get its length
len(d)
Out[50]:
In [51]:
# clear dictionary but don't delete it
d.clear()
d
Out[51]:
In [52]:
# create a dictionary
d = {'Name': 'Jimmy',
"phone": '850-882-0340',
"Work": "Eglin AFB"}
In [53]:
# check for key
d.has_key('name')
Out[53]:
In [54]:
# get the items of a dictionary
d.items()
Out[54]:
In [55]:
# just get the keys
d.keys()
Out[55]:
In [56]:
# just get the values
d.values()
Out[56]:
In [57]:
# print both the keys and values
for k,v in d.items():
print k,v
In [58]:
# copy a dictionay
dd = d
print dd is d
print d,dd
In [59]:
dd['Name']='Alex'
In [126]:
d,dd
Out[126]:
In [60]:
# change a value
d['Name'] = 'JT'
d,dd
Out[60]:
In [128]:
dd is d
Out[128]:
In [61]:
# another way to copy dictionaries
dd = d.copy()
print dd is d
print d,dd
In [62]:
# change a value
dd['Name']='Alex'
d,dd
Out[62]:
In [63]:
d['Name'] = 'JT'
d,dd
Out[63]:
In [34]:
# nesting - no restrictions on value
rec = {'name': {'first': ['bob', 'mob'], 'last': 'Smith'},
'jobs': ['dev', 'mgr'],
'age': 40.5}
print rec
In [35]:
rec.keys()
Out[35]:
In [36]:
rec.values()
Out[36]:
In [37]:
# access the first element
rec['name']
Out[37]:
In [38]:
rec['name']['first']
Out[38]:
In [40]:
rec['name']['first'][1]
Out[40]: