Saturday, July 2, 2022

Python - Dictionaries

# Dictionaries

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}

# {'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
print(thisdict)

# Ford
print(thisdict["brand"])

# 3
print(len(thisdict))

mymodel = thisdict["model"]

# Mustang
print (mymodel)

mykeys = thisdict.keys()

# dict_keys(['brand', 'model', 'year'])
print (mykeys)

myvalues = thisdict.values()
# dict_values(['Ford', 'Mustang', 1964])
print (myvalues)

myitems = thisdict.items()
# dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year', 1964)])
print (myitems)

print("---")

thisdict =    {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}

# Change a value
thisdict["year"] = 2018
# 2018
print(thisdict["year"])


thisdict.update({"year": 2020})
# 2020
print(thisdict["year"])

# Add an item
thisdict["color"] = "red"
# {'brand': 'Ford', 'model': 'Mustang', 'year': 2020, 'color': 'red'}
print (thisdict)

# This updates the value
# If the value does not exist, it will add it
thisdict.update({"color": "blue"})
thisdict.update({"wheels": 4})
# {'brand': 'Ford', 'model': 'Mustang', 'year': 2020, 'color': 'blue', 'wheels': 4}
print (thisdict)


# Pop removes the last inserted item and returns the item
# 5
print(len(thisdict))
x = thisdict.popitem()
# ('wheels', 4)
print(x)
# 4
print(len(thisdict))


del thisdict["color"]
del thisdict["model"]
# {'brand': 'Ford', 'year': 2020}
print(thisdict)

# Clear the dictionary of all items
thisdict.clear()
# {}
print(thisdict)

# Remove the dictionary completely
del thisdict
# Next line will cause an error
#print(thisdict)

print("---")
thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}

# This will loop through and show the keys
# brand
# model
# year
for x in thisdict:
    print(x)

# This will loop through and show the values
# Ford
# Mustang
# 1964
for x in thisdict:
    print(thisdict[x])

print("---")

# Ford
# Mustang
# 1964
for x in thisdict.values():
    print(x)

# brand
# model
# year
for x in thisdict.keys():
    print(x)

print("---")

# Gnarly - loop through both keys and values
# brand Ford
# model Mustang
# year 1964

for x, y in thisdict.items():
  print(x, y)

print("======")

 
# Copy a dictionary
# Truly a copy and not a reference
thisdict =    {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
mydict = thisdict.copy()
print(mydict)

print("---")

mydict["year"] = 2020

print(mydict)

print(thisdict)

print("---")

myfamily = {
  "child1" : {
    "name" : "Emil",
    "year" : 2004
  },
  "child2" : {
    "name" : "Tobias",
    "year" : 2007
  },
  "child3" : {
    "name" : "Linus",
    "year" : 2011
  }
}

# <class 'dict'>
print(type(myfamily))
# <class 'dict'>
print(type(myfamily["child1"]))

# {'name': 'Emil', 'year': 2004}
print(myfamily["child1"])

# Emil
print(myfamily["child1"]["name"])
# <class 'str'>
print(type(myfamily["child1"]["name"]))