Day 52: The Wholesome World Of Dictionaries

# dictionaries
import collections
# creating a dictionary
data = {"first" : "Linus", "last" : "of Paros"}

# add keys and values
data["age"] = 3
data["job"] = "Dog"

print(data)                     # {'first': 'Linus', 'last': 'of Paros', 'age': 3, 'job': 'Dog'}

#retrieving values
print(data["first"])            # Linus

print(data["first"] + " " + data["last"] + " is a " + data["job"] ) # Linus of Paros is a Dog

# check if a key is in the dict with in operator
print("first" in data)          # True
print("car" in data)            # False

# with get you can set a default in case a key is not found in a dict
shortcut = data.get("address", "unknown")

print(shortcut)                 # unknown

# remove keys and values
numbers = {"1" : "true", "2" : "false","2" : "false", "3" : "true"}

del numbers["2"]

print(numbers)                  # {'1': 'true', '3': 'true'}

# iterating over dictionaries
age = {"Don" : 55, "Cindy" : 52, "James" : 42, "Sara" : 35}

for name in age:
    print(name)                 # Don, Cindy, James, Sara

for name in age.values():
    print(name)                 # 55, 52, 42, 35

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.

Diese Website verwendet Akismet, um Spam zu reduzieren. Erfahre mehr darüber, wie deine Kommentardaten verarbeitet werden.