Dictionaries
# method 1
>>> D = {"Captain Marvel": 3, "Living Tribunal": 2, "One-Above-All": 1}
# method 2
>>> CHARACTERS = ["Captain Marvel", "Living Tribunal", "One-Above-All"]
>>> RANK = [3, 2, 1]
>>> D = dict(zip(CHARACTERS, RANK))
>>> print(D)
{"Captain Marvel": 3, "Living Tribunal": 2, "One-Above-All": 1}# the dictionary
>>> D = {"Captain Marvel": 3, "Living Tribunal": 2, "One-Above-All": 1}
# let's fetch Captain Marvel's position in the Marvel characters' power rank
>>> D["Captain Marvel"]
3
# a dictionary of dictionaries
>>> D = {
"Dr. Strange": {
"first_appearance": 1963,
"created_by": "Lee & Ditko"
},
"Iron Man": {
"first_appearance": 1963,
"created_by": "Lee, Lieber, Heck & Kirby"
},
}
# let us fetch the creator of Dr. Strange
>>> D["Dr. Strange"]["created_by"]
"Lee & Ditko"# the dictionary
>>> D = {"Captain Marvel": 3, "Living Tribunal": 2, "One-Above-All": 1}
# let us change the power rank for Captain Marvel
>>> D["Captain Marvel"] = 12
>>> print(D)
{"Captain Marvel": 12, "Living Tribunal": 2, "One-Above-All": 1}
# let us eliminate the character Living Tribunal
>>> del D["Living Tribunal"]
>>> print(D)
{"Captain Marvel": 12, "One-Above-All": 1}
# let us add a further character
>>> D["Wanda Maximoff"] = 4
>>> print(D)
{"Captain Marvel": 12, "One-Above-All": 1, "Wanda Maximoff": 4}| Method | Synopsis |
|---|---|
D.keys() |
Get all dictionary keys |
D.values() |
Get all dictionary values |
D.items() |
Get all dictionary key-value pairs as tuples |
D.get(key, default?) |
Query a dictionary element by key |
D.update(D2) |
Update a dictionary key’s value |
D.popitem() |
Remove the value corresponding to a certain key |
D.pop(key, default?) |
Remove the item at the given position in the list |
D.clear() |
Delete all dictionary items |
D.copy() |
Copy the target dictionary |
# the dictionary
>>> D = {"Captain Marvel": 3, "Living Tribunal": 2, "One-Above-All": 1}
# get the keys
>>> D.keys()
dict_keys(["Captain Marvel", "Living Tribunal", "One-Above-All"])
# get the values
>>> D.values()
dict_values([3, 2, 1])
# get the items
>>> D.items()
dict_items([("Captain Marvel", 3), ("Living Tribunal", 2), ("One-Above-All", 1)])
# get the keys as a list
>>> list(D.keys())
["Captain Marvel", "Living Tribunal", "One-Above-All"]