How do you create a dictionary in python? Flashcards

(5 cards)

1
Q

Key Concepts of a dict

A

A dictionary in Python contains a collection of key:value pairs.

Keys must be unique and are typically immutable, such as strings, numbers, or tuples.

Values can be of any type, and they can be duplicated.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Creating a Dictionary

A
  • You can use several methods to create a dictionary:

Literal Definition: Define key-value pairs within curly braces { }.

  • From Key-Value Pairs: Use the dict() constructor or the {key: value} shorthand.
  • Using the dict() Constructor: This can accept another dictionary, a sequence of key-value pairs, or named arguments.
  • Comprehensions: This is a concise way to create dictionaries using a single line of code. (may need to find an example)
  • zip() Function: This creates a dictionary by zipping two lists, where the first list corresponds to the keys, and the second to the values.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

zip() example

A
keys = ["a", "b", "c"]
values = [1, 2, 3]

zipped = zip(keys, values)
dict_from_zip = dict(zipped) # Result: {"a": 1, "b": 2, "c": 3}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Key-Value Pairs example

A
# Using the `dict()` constructor
student_dict = dict([
    ("name", "John Doe"),
    ("age", 21),
    ("courses", ["Math", "Physics"])
])

Using the shorthand syntax
student_dict_short = {
    "name": "John Doe",
    "age": 21,
    "courses": ["Math", "Physics"]
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

dict() Constructor example

A
# Sequence of key-value pairs
student_dict2 = dict(name="Jane Doe", age=22, courses=["Biology", "Chemistry"])

From another dictionary
student_dict_combined = dict(student, **student_dict2)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly