Professional Documents
Culture Documents
In [1]:
1 dict={}
2 type(dict)
Out[1]:
dict
2. What is the value of a dictionary value with the key 'foo' and the value 42?
In [8]:
1
2 d={"key":"foo","value":42}
3 d
Out[8]:
In [ ]:
In [7]:
1 spam={'bar':100}
2 spam['foo']
---------------------------------------------------------------------------
<ipython-input-7-3fa7eee1403a> in <module>
1 spam={'bar':100}
----> 2 spam['foo']
KeyError: 'foo'
5. If a dictionary is stored in spam, what is the difference between the expressions 'cat' in spam and 'cat' in
spam.keys()?
Answer:There is no differnce, both check if 'cat' is key of the dictionary and if its a key,
p y () , y y y,
returns True.
In [11]:
1 spam={'cat':100}
2 'cat' in spam
Out[11]:
True
In [12]:
1 spam={'cat':100}
2 'cat' in spam.keys()
Out[12]:
True
6. If a dictionary is stored in spam, what is the difference between the expressions 'cat' in spam and 'cat' in
spam.values()?
Answer:
'cat' in spam checks whether there is a 'cat' key in the dictionary
'cat' in
spam.values() checks whether there is a value 'cat' for one of the keys in spam.
In [13]:
1 spam={'cat':100}
2 'cat' in spam
Out[13]:
True
In [14]:
1 spam={'cat':100}
2 'cat' in spam.values()
Out[14]:
False
1 spam ={'cat':100}
2 spam.setdefault('color','black')
3 spam
Out[15]:
8. How do you "pretty print" dictionary values using which module and function?
Pretty printing means to
present something in a more readable format or style
In [2]:
1 import pprint
In [3]:
In [4]:
1 pprint.pprint(dct_arr)
In [5]:
1 print(dct_arr)
In [ ]: