Dictionary
Construct a Dictionary
a = {"first": "John", "last": "Smith"} # {'first': 'John', 'last': 'Smith'}
# from a list of tuples
b = dict([("first", "John"), ("last", "Smith")])
# from keyword arguments
c = dict(first="John", last="Smith")
# from dictionary comprehension
d = {x: x**2 for x in range(10)} # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
Loop Through Items
a = {"domain": "literank.com", "services": 29, "year": 2017}
for k, v in a.items():
print(k, '->', v)
Add/Update Item
a = {"first": "John", "last": "Smith"} # {'first': 'John', 'last': 'Smith'}
a["age"] = 26
a["first"] = "Tom"
print(a) # {'first': 'Tom', 'last': 'Smith', 'age': 26}
Check If Key Exists
a = {"first": "John", "last": "Smith"}
print("first" in a) # True
print("age" in a) # False
Dictionary's Common Methods
fromkeys
a = ['a', 'b', 'c']
b = dict.fromkeys(a, 10) # 10 is the default value for all keys
print(b) # {'a': 10, 'b': 10, 'c': 10}
clear
a = {"first": "John", "last": "Smith"}
a.clear()
print(a) # {}
get
a = {"first": "John", "last": "Smith"}
print(a.get("first")) # John
print(a.get("age", 28)) # 28
get's function signature is get(key[, default])
. Return the value for key if key is in the dictionary, else default.
If default is not given, it defaults to None
, so that this method never raises a KeyError.
setdefault
a = {"first": "John", "last": "Smith"}
a.setdefault("first", "Tom")
a.setdefault("age", "12")
print(a) # {'first': 'John', 'last': 'Smith', 'age': '12'}
setdefault's function signature is setdefault(key[, default])
. If key is in the dictionary, return its value.
If not, insert key with a value of default and return default. default defaults to None
.
Unpack a Dictionary
def passport_check(first, last):
print(f"{first} {last} is ok to go!")
a = {"first": "John", "last": "Smith"}
# unpack with double asterisks
passport_check(**a) # John Smith is ok to go!
Code Challenge
Try to modify the code provided in the editor to swap key-value pairs in the dictionary.
e.g. {'a': 'b'} to {'b': 'a'}
Loading...
> code result goes here