Dictionary 1
Dictionary 1
------------------
You cannot copy a dictionary simply by typing dict2 = dict1, because: dict2 will
only be a reference to dict1, and changes made in dict1 will automatically also be
made in dict2.
There are ways to make a copy, one way is to use the built-in Dictionary method
copy().
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
mydict = thisdict.copy()
print(mydict)
Nested Dictionaries
A dictionary can contain dictionaries, this is called nested dictionaries.
Example
Create three dictionaries, then create one dictionary that will contain the other
three dictionaries:
child1 = {
"name" : "Emil",
"year" : 2004
}
child2 = {
"name" : "Tobias",
"year" : 2007
}
child3 = {
"name" : "Linus",
"year" : 2011
}
myfamily = {
"child1" : child1,
"child2" : child2,
"child3" : child3
}
Example
Print the name of child 2:
print(myfamily["child2"]["name"])
for y in obj:
print(y + ':', obj[y])
thisdict = dict.fromkeys(x, y)
print(thisdict)
The setdefault() method returns the value of the item with the specified key.
If the key does not exist, insert the key, with the specified value
Example
Get the value of the "color" item, if the "color" item does not exist, insert
"color" with the value "white":
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.setdefault("color", "white")
print(x)
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.get("model")
print(x)