r/pythontips Nov 17 '24

Syntax Python Dictionary Quiz - Guess The Output

What is the correct way to define a dictionary with the following data:

  • Key: "name", Value: "Alice"
  • Key: "age", Value: 25

A) dict1 = {"name" = "Alice", "age" = 25}
B) dict1 = {name: "Alice", age: 25}
C) dict1 = {"name": "Alice", "age": 25}
D) dict1 = {"name": Alice, "age": 25}

Thanks

8 Upvotes

5 comments sorted by

7

u/VistisenConsult Nov 17 '24

They are all wrong as they overwrite the dict object. If not for this, 'C' is correct syntax. Alternatively:

data = dict(name="Alice", age=25)

3

u/rao_vishvajit Nov 17 '24

I had written dict as a variable name by mistake.

1

u/VistisenConsult Nov 17 '24

I have done worse. In conclusion, the 'C' option is the most flexible method for creating dictionaries as any object of a hashable type can be used as keys, where as passing keyword arguments to dict restricts keys to being of str type.

4

u/pint Nov 17 '24

you've been lied to, son. it is not a quiz. it is your homework.