0% found this document useful (0 votes)
11 views2 pages

Dictionary 1

Uploaded by

ranganadh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views2 pages

Dictionary 1

Uploaded by

ranganadh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

Copy a Dictionary

------------------
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().

Make a copy of a dictionary with the copy() method:

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
}

Access Items in Nested Dictionaries


To access items from a nested dictionary, you use the name of the dictionaries,
starting with the outer dictionary:

Example
Print the name of child 2:

print(myfamily["child2"]["name"])

Loop Through Nested Dictionaries


You can loop through a dictionary by using the items() method like this:
Example
Loop through the keys and values of all nested dictionaries:

for x, obj in myfamily.items():


print(x)

for y in obj:
print(y + ':', obj[y])

ExampleGet your own Python Server


Create a dictionary with 3 keys, all with the value 0:

x = ('key1', 'key2', 'key3')


y = 0

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)

Get the value of the "model" item:

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

x = car.get("model")

print(x)

You might also like