Note_Tech

All technological notes.


Project maintained by simonangel-fong Hosted on GitHub Pages — Theme by mattgraham

Python - Dictionary

Back


Dictionary


Dictionary Methods


Create a dictionary

# create a list

print("\n--------Create a Dictionary--------\n")
xdict = {
    "brand": "Ford",
    "model": "Mustang",
    "year": 1964,       # will be rewritten, not allow to duplicate
    "year": 2020
}
print(xdict)            # {'name': 'John', 'age': 36, 'country': 'Norway'}


xdict = dict(name="John", age=36, country="Norway")
print(xdict)            # {'name': 'John', 'age': 36, 'country': 'Norway'}

xdict = dict()
print(type(xdict))      # <class 'dict'>
print(xdict)            # {}

xdict = {}
print(type(xdict))      # <class 'dict'>
print(xdict)            # {}


Access Items

print("\n--------Access Items--------\n")

print("\n--------[key_name]--------\n")
# by key_name
xdict = {
    "brand": "Ford",
    "model": "Mustang",
    "year": 1964
}
value = xdict["model"]
print(value)            # Mustang


print("\n--------.get('key_name')--------\n")
# get()
xdict = {
    "brand": "Ford",
    "model": "Mustang",
    "year": 1964
}
value = xdict.get("model")
print(value)            # Mustang


print("\n--------.keys():dict_keys--------\n")
xdict = {
    "brand": "Ford",
    "model": "Mustang",
    "year": 1964
}
keys = xdict.keys()
print(keys)                    # dict_keys(['brand', 'model', 'year'])
print(type(keys))              # <class 'dict_keys'>
# print(keys[0])                 # TypeError: 'dict_keys' object is not subscriptable
# print(keys["brand"])           # TypeError: 'dict_keys' object is not subscriptable

for k in keys:
    print(k)
# brand
# model
# year

print(list(keys)[0])           # brand

xdict["year"] = 2020
keys = xdict.keys()
# value list updated: dict_keys(['brand', 'model', 'year'])
print(keys)

xdict["color"] = "red"
keys = xdict.keys()
# value list updated: dict_keys(['brand', 'model', 'year', 'color'])
print(keys)


print("\n--------.values():dict_values--------\n")
xdict = {
    "brand": "Ford",
    "model": "Mustang",
    "year": 1964
}
values = xdict.values()
print(values)                    # dict_values(['Ford', 'Mustang', 1964])
print(type(values))              # <class 'dict_values'>
# print(values[0])                 # TypeError: 'dict_values' object is not subscriptable
# print(values["brand"])           # TypeError: 'dict_values' object is not subscriptable

for i in values:
    print(i)
# Ford
# Mustang
# 1964

print(list(values)[0])           # Ford

xdict["year"] = 2020
values = xdict.values()
# value list updated: dict_values(['Ford', 'Mustang', 2020])
print(values)

xdict["color"] = "red"
values = xdict.values()
# value list updated: dict_values(['Ford', 'Mustang', 2020, 'red'])
print(values)


print("\n--------.items():dict_items--------\n")
xdict = {
    "brand": "Ford",
    "model": "Mustang",
    "year": 1964
}
items = xdict.items()
# dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year', 1964)])
print(items)
print(type(items))              # <class 'dict_items'>
# print(items[0])                 # TypeError: 'dict_items' object is not subscriptable
# print(items["brand"])           # TypeError: 'dict_items' object is not subscriptable

for i in items:
    print(i)
# ('brand', 'Ford')
# ('model', 'Mustang')
# ('year', 1964)

print(list(items)[0])           # ('brand', 'Ford')

xdict["year"] = 2020
items = xdict.items()
# value list updated: dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year', 2020)])
print(items)

xdict["color"] = "red"
items = xdict.items()
# value list updated: dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year', 2020), ('color', 'red')])
print(items)


Add Dictionary Items


print("\n--------Add Items--------\n")
# using key name
xDict = {
    "brand": "Ford",
    "model": "Mustang",
    "year": 1964
}
xDict["color"] = "red"
# {'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color': 'red'}
print(xDict)


# update()
xDict = {
    "brand": "Ford",
    "model": "Mustang",
    "year": 1964
}
xDict.update({"color": "red"})
# {'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color': 'red'}
print(xDict)


Change Item Value


print("\n--------Change Item Value--------\n")
# using key name
xDict = {
    "brand": "Ford",
    "model": "Mustang",
    "year": 1964
}
xDict["year"] = 2018

print(xDict)    # {'brand': 'Ford', 'model': 'Mustang', 'year': 2018}


# update()
xDict.update({"year": 2020})

print(xDict)    # {'brand': 'Ford', 'model': 'Mustang', 'year': 2020}

Remove Dict Items

print("\n--------Remove Items--------\n")
# pop()
xDict = {
    "brand": "Ford",
    "model": "Mustang",
    "year": 1964
}
remove_value = xDict.pop("model")
print(remove_value)                 # Mustang
print(xDict)                        # {'brand': 'Ford', 'year': 1964}


# popitem
xDict = {
    "brand": "Ford",
    "model": "Mustang",
    "year": 1964
}
remove_item = xDict.popitem()
print(remove_item)                  # ('year', 1964)
print(xDict)                        # {'brand': 'Ford', 'model': 'Mustang'}


# del
xDict = {
    "brand": "Ford",
    "model": "Mustang",
    "year": 1964
}

del xDict["model"]
print(xDict)                        # {'brand': 'Ford', 'year': 1964}

del xDict
# print(xDict)                        # NameError: name 'xDict' is not defined


# clear()
xDict = {
    "brand": "Ford",
    "model": "Mustang",
    "year": 1964
}
xDict.clear()
print(xDict)                        # {}

Check if Key Exists: in

xDict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
if "model" in xDict:
  print("Yes, 'model' is one of the keys in the xDict dictionary")


Loop Dictionaries


print("\n--------for in loop--------\n")

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

# loop keys
for x in xDict:
    print(x)
# brand
# model
# year

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


# loop values
for x in xDict:
    print(xDict[x])
# Ford
# Mustang
# 1964

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


# loop items
for x in xDict.items():
    print(x)
# ('brand', 'Ford')
# ('model', 'Mustang')
# ('year', 1964)

for x, y in xDict.items():
    print(x, y)
# brand Ford
# model Mustang
# year 1964

Copy Dictionaries


print("\n--------Copy dict: copy()--------\n")

xDict = {
    "brand": "Ford",
    "model": "Mustang",
    "year": 1964
}
yDict = xDict.copy()

xDict.update({"year": 2020})

print(xDict)            # {'brand': 'Ford', 'model': 'Mustang', 'year': 2020}
print(yDict)            # {'brand': 'Ford', 'model': 'Mustang', 'year': 1964}


print("\n--------Copy dict: dict()--------\n")

xDict = {
    "brand": "Ford",
    "model": "Mustang",
    "year": 1964
}
yDict = dict(xDict)

xDict.update({"year": 2020})

print(xDict)            # {'brand': 'Ford', 'model': 'Mustang', 'year': 2020}
print(yDict)            # {'brand': 'Ford', 'model': 'Mustang', 'year': 1964}

Nested Dictionaries


print("\n--------Nested Dictionary--------\n")

xDict = {
    "child1": {
        "name": "Emil",
        "year": 2004
    },
    "child2": {
        "name": "Tobias",
        "year": 2007
    },
    "child3": {
        "name": "Linus",
        "year": 2011
    }
}
# {'child1': {'name': 'Emil', 'year': 2004}, 'child2': {'name': 'Tobias', 'year': 2007}, 'child3': {'name': 'Linus', 'year': 2011}}
print(xDict)

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

xDict = {
    "child1": child1,
    "child2": child2,
    "child3": child3
}
# {'child1': {'name': 'Emil', 'year': 2004}, 'child2': {'name': 'Tobias', 'year': 2007}, 'child3': {'name': 'Linus', 'year': 2011}}
print(xDict)


print("\n--------Access inner value--------\n")

print(xDict["child2"]["name"])  # Tobias


fromkeys()

print("\n--------fromkeys()--------\n")
keys = ('key1', 'key2', 'key3')
xDict = dict.fromkeys(keys)

print(xDict)     # {'key1': None, 'key2': None, 'key3': None}


xDict = dict.fromkeys(('key1',), 'value1')
xDict = dict.fromkeys(('key2',), 'value2')

print(xDict)     # {'key2': 'value2'}


setdefault()


print("\n--------setdefault()--------\n")
car = {
    "brand": "Ford",
    "model": "Mustang",
    "year": 1964
}

# If the key exist, this parameter has no effect.
x = car.setdefault("model", "Bronco")

print(x)    # Mustang


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

# If the key does not exist, this value becomes the key's value
x = car.setdefault("color", "white")

print(x)    # white

TOP