You are on page 1of 3

1. What does an empty dictionary's code look like?

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]:

{'key': 'foo', 'value': 42}

3. What is the most significant distinction between a dictionary and a list?

Answer:distinction between a dictionary and a list:

List:The elements in the list is ordered

dictionary:The elements in the list is not ordered

In [ ]: 

1 4. What happens if you try to access spam['foo'] if spam is {'bar': 100}?


2
3 Answer:This gives as key error

In [7]: 

1 spam={'bar':100}
2 spam['foo']

---------------------------------------------------------------------------

KeyError Traceback (most recent call last)

<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

7. What is a shortcut for the following code?


if 'color' not in spam:
spam['color'] = 'black'
This can be achieved
by using setdefault() which Inserts key with a value of default if key is not in the dictionary
In [15]: 

1 spam ={'cat':100}
2 spam.setdefault('color','black')
3 spam

Out[15]:

{'cat': 100, 'color': 'black'}

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]: 

1 dct_arr = [ {'Name': 'arvind', 'Age': '44', 'Country': 'India'},


2 {'Name': 'Ramya', 'Age': '36', 'Country': 'Spain'},
3 {'Name': 'Evana', 'Age': '21', 'Country': 'UK'},
4 {'Name': 'Raj', 'Age': '18', 'Country': 'Japan'}
5 ]

In [4]: 

1 pprint.pprint(dct_arr)

[{'Age': '44', 'Country': 'India', 'Name': 'arvind'},

{'Age': '36', 'Country': 'Spain', 'Name': 'Ramya'},

{'Age': '21', 'Country': 'UK', 'Name': 'Evana'},

{'Age': '18', 'Country': 'Japan', 'Name': 'Raj'}]

In [5]: 

1 print(dct_arr)

[{'Name': 'arvind', 'Age': '44', 'Country': 'India'}, {'Name': 'Ramya', 'Ag


e': '36', 'Country': 'Spain'}, {'Name': 'Evana', 'Age': '21', 'Country': 'U
K'}, {'Name': 'Raj', 'Age': '18', 'Country': 'Japan'}]

In [ ]: 

You might also like