Question 7, Quiz 5

Which of the following is not a valid way to define this dictionary in Python:

a) d = {} d[‘foo’] = 100 d[‘bar’] = 200 d[‘baz’] = 300
b) d = {(‘foo’, 100), (‘bar’, 200), (‘baz’, 300) }
c) d = dict(foo=100, bar=200, baz=300)
d) d = dict([(‘foo’, 100), (‘bar’, 200), (‘baz’, 300) ])

In above question option a&b both are invalid forms to define dictionary, Kindly update this answer as well.

1 Like

@parulr1096
As I know b will the answer because
Option (b) is not a valid way to define the dictionary in Python because it is using parentheses instead of curly braces to define a dictionary. Instead, it defines a set of tuples, where each tuple contains a key-value pair of the dictionary.

Option (a) uses the empty curly braces {} to define an empty dictionary, and then uses the square bracket [] to add key-value pairs to the dictionary. Option (c) uses the dict() constructor and keyword arguments to define the dictionary. Option (d) uses the dict() constructor and a list of tuples to define the dictionary.

Hope this will help

2 Likes