Dictionaries

In [1]:
d = dict()  # class constructor for dictionaries
d = {} # literal definition of a dict
In [2]:
passwd = {
    "guido": "superprogrammer",
    "turing": "genius",
    "bill": "monopoly"
}
In [3]:
passwd['guido']
Out[3]:
'superprogrammer'
In [4]:
passwd['bill']
Out[4]:
'monopoly'
In [6]:
try:
    print(passwd['steve'])
except KeyError:
    print("Key 'steve' not found!")
Key 'steve' not found!
In [7]:
try:
    print(passwd['steve'])
except KeyError:
    print("Key 'steve' not found!")
    p = input("Please enter a new password for them: ")
    passwd['steve'] = p
Key 'steve' not found!
Please enter a new password for them: visionary
In [9]:
passwd
Out[9]:
{'bill': 'monopoly',
 'guido': 'superprogrammer',
 'steve': 'visionary',
 'turing': 'genius'}
In [14]:
from math import pi
pi_s = str(pi)
pi_slices = list(pi_s)
In [16]:
mapping = {}
mapping[235] = "A number, an int!"
mapping[pi] = pi_slices
mapping[(43.1566, 77.6088)] = "Geographical location for Rochester, NY"
In [18]:
print(mapping)
{235: 'A number, an int!', 3.141592653589793: ['3', '.', '1', '4', '1', '5', '9', '2', '6', '5', '3', '5', '8', '9', '7', '9', '3'], (43.1566, 77.6088): 'Geographical location for Rochester, NY'}

Dictionary Methods

in with dict

In [19]:
passwd
Out[19]:
{'bill': 'monopoly',
 'guido': 'superprogrammer',
 'steve': 'visionary',
 'turing': 'genius'}
In [20]:
if "bezos" in passwd:
    print("Jeff's user account is found, his password is {0}".format(passwd['bezos']))
else:
    print("Key 'bezos' not found!")
    p = input("Please enter a new password for him: ")
    passwd['bezos'] = p
Key 'bezos' not found!
---------------------------------------------------------------------------
KeyboardInterrupt                         Traceback (most recent call last)
/usr/local/lib/python3.6/site-packages/ipykernel/kernelbase.py in _input_request(self, prompt, ident, parent, password)
    728             try:
--> 729                 ident, reply = self.session.recv(self.stdin_socket, 0)
    730             except Exception:

/usr/local/lib/python3.6/site-packages/jupyter_client/session.py in recv(self, socket, mode, content, copy)
    802         try:
--> 803             msg_list = socket.recv_multipart(mode, copy=copy)
    804         except zmq.ZMQError as e:

/usr/local/lib/python3.6/site-packages/zmq/sugar/socket.py in recv_multipart(self, flags, copy, track)
    465         """
--> 466         parts = [self.recv(flags, copy=copy, track=track)]
    467         # have first part already, only loop while more to receive

zmq/backend/cython/socket.pyx in zmq.backend.cython.socket.Socket.recv()

zmq/backend/cython/socket.pyx in zmq.backend.cython.socket.Socket.recv()

zmq/backend/cython/socket.pyx in zmq.backend.cython.socket._recv_copy()

/usr/local/lib/python3.6/site-packages/zmq/backend/cython/checkrc.pxd in zmq.backend.cython.checkrc._check_rc()

KeyboardInterrupt: 

During handling of the above exception, another exception occurred:

KeyboardInterrupt                         Traceback (most recent call last)
<ipython-input-20-b05f0e858970> in <module>()
      3 else:
      4     print("Key 'bezos' not found!")
----> 5     p = input("Please enter a new password for him: ")
      6     passwd['bezos'] = p

/usr/local/lib/python3.6/site-packages/ipykernel/kernelbase.py in raw_input(self, prompt)
    702             self._parent_ident,
    703             self._parent_header,
--> 704             password=False,
    705         )
    706 

/usr/local/lib/python3.6/site-packages/ipykernel/kernelbase.py in _input_request(self, prompt, ident, parent, password)
    732             except KeyboardInterrupt:
    733                 # re-raise KeyboardInterrupt, to truncate traceback
--> 734                 raise KeyboardInterrupt
    735             else:
    736                 break

KeyboardInterrupt: 

.keys()

In [26]:
keys = passwd.keys()
In [36]:
for key in keys:
    print(key, passwd[key])
guido superprogrammer
turing genius
bill monopoly
steve visionary
In [29]:
keys = list(passwd.keys())
In [30]:
keys[0]
Out[30]:
'guido'

.values()

In [31]:
vals = passwd.values()
In [32]:
vals
Out[32]:
dict_values(['superprogrammer', 'genius', 'monopoly', 'visionary'])
In [33]:
for val in vals:
    print(val)
superprogrammer
genius
monopoly
visionary
In [34]:
vals = list(vals)
In [35]:
vals
Out[35]:
['superprogrammer', 'genius', 'monopoly', 'visionary']

.items()

In [37]:
items = passwd.items()
In [38]:
items
Out[38]:
dict_items([('guido', 'superprogrammer'), ('turing', 'genius'), ('bill', 'monopoly'), ('steve', 'visionary')])
In [39]:
for key, val in items:
    print(key, val)
guido superprogrammer
turing genius
bill monopoly
steve visionary

.get()

In [40]:
passwd['bezos']
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-40-e38f99b0a953> in <module>()
----> 1 passwd['bezos']

KeyError: 'bezos'
In [42]:
p = passwd.get('bezos')
print(p)
None
In [43]:
p = passwd.get('bezos', False)
print(p)
False
In [44]:
p = passwd.get('bezos', "Bezos not found!")
print(p)
Bezos not found!

del on dict

In [45]:
passwd['joe'] = "tortured visionary"
In [46]:
passwd
Out[46]:
{'bill': 'monopoly',
 'guido': 'superprogrammer',
 'joe': 'tortured visionary',
 'steve': 'visionary',
 'turing': 'genius'}
In [47]:
del passwd['joe']
In [48]:
passwd
Out[48]:
{'bill': 'monopoly',
 'guido': 'superprogrammer',
 'steve': 'visionary',
 'turing': 'genius'}

Looping of keys

In [49]:
for key in passwd.keys():
    print(key, passwd[key])
guido superprogrammer
turing genius
bill monopoly
steve visionary
In [50]:
for key in passwd:
    print(key, passwd[key])
guido superprogrammer
turing genius
bill monopoly
steve visionary

.pop()

In [55]:
passwd.pop('bezos')
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-55-dcc9b236b233> in <module>()
----> 1 passwd.pop('bezos')

KeyError: 'bezos'
In [56]:
passwd.pop('bezos', False)
Out[56]:
False
In [58]:
passwd.pop('turing')
Out[58]:
'genius'
In [59]:
passwd
Out[59]:
{'bill': 'monopoly', 'guido': 'superprogrammer', 'steve': 'visionary'}
In [51]:
help(dict)
Help on class dict in module builtins:

class dict(object)
 |  dict() -> new empty dictionary
 |  dict(mapping) -> new dictionary initialized from a mapping object's
 |      (key, value) pairs
 |  dict(iterable) -> new dictionary initialized as if via:
 |      d = {}
 |      for k, v in iterable:
 |          d[k] = v
 |  dict(**kwargs) -> new dictionary initialized with the name=value pairs
 |      in the keyword argument list.  For example:  dict(one=1, two=2)
 |  
 |  Methods defined here:
 |  
 |  __contains__(self, key, /)
 |      True if D has a key k, else False.
 |  
 |  __delitem__(self, key, /)
 |      Delete self[key].
 |  
 |  __eq__(self, value, /)
 |      Return self==value.
 |  
 |  __ge__(self, value, /)
 |      Return self>=value.
 |  
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 |  
 |  __getitem__(...)
 |      x.__getitem__(y) <==> x[y]
 |  
 |  __gt__(self, value, /)
 |      Return self>value.
 |  
 |  __init__(self, /, *args, **kwargs)
 |      Initialize self.  See help(type(self)) for accurate signature.
 |  
 |  __iter__(self, /)
 |      Implement iter(self).
 |  
 |  __le__(self, value, /)
 |      Return self<=value.
 |  
 |  __len__(self, /)
 |      Return len(self).
 |  
 |  __lt__(self, value, /)
 |      Return self<value.
 |  
 |  __ne__(self, value, /)
 |      Return self!=value.
 |  
 |  __new__(*args, **kwargs) from builtins.type
 |      Create and return a new object.  See help(type) for accurate signature.
 |  
 |  __repr__(self, /)
 |      Return repr(self).
 |  
 |  __setitem__(self, key, value, /)
 |      Set self[key] to value.
 |  
 |  __sizeof__(...)
 |      D.__sizeof__() -> size of D in memory, in bytes
 |  
 |  clear(...)
 |      D.clear() -> None.  Remove all items from D.
 |  
 |  copy(...)
 |      D.copy() -> a shallow copy of D
 |  
 |  fromkeys(iterable, value=None, /) from builtins.type
 |      Returns a new dict with keys from iterable and values equal to value.
 |  
 |  get(...)
 |      D.get(k[,d]) -> D[k] if k in D, else d.  d defaults to None.
 |  
 |  items(...)
 |      D.items() -> a set-like object providing a view on D's items
 |  
 |  keys(...)
 |      D.keys() -> a set-like object providing a view on D's keys
 |  
 |  pop(...)
 |      D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
 |      If key is not found, d is returned if given, otherwise KeyError is raised
 |  
 |  popitem(...)
 |      D.popitem() -> (k, v), remove and return some (key, value) pair as a
 |      2-tuple; but raise KeyError if D is empty.
 |  
 |  setdefault(...)
 |      D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D
 |  
 |  update(...)
 |      D.update([E, ]**F) -> None.  Update D from dict/iterable E and F.
 |      If E is present and has a .keys() method, then does:  for k in E: D[k] = E[k]
 |      If E is present and lacks a .keys() method, then does:  for k, v in E: D[k] = v
 |      In either case, this is followed by: for k in F:  D[k] = F[k]
 |  
 |  values(...)
 |      D.values() -> an object providing a view on D's values
 |  
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |  
 |  __hash__ = None