Python Dictionaries
- Previous Page Python Sets
- Next Page Python If Else
Dictionary (Dictionary)
A dictionary is an unordered, mutable, and indexed collection. In Python, dictionaries are written using curly braces and have keys and values.
Instance
Create and print the dictionary:
thisdict = { "brand": "Porsche", "model": "911", "year": 1963 } print(thisdict)
Access item
You can access the items of the dictionary by referencing its key name within brackets:
Instance
Get the value of the "model" key:
x = thisdict["model"]
There is also a named get()
method will give you the same result:
Instance
Get the value of the "model" key:
x = thisdict.get("model")
Change value
You can change the value of a specific item by referencing its key name:
Instance
Change "year" to 2019:
thisdict = { "brand": "Porsche", "model": "911", "year": 1963 } thisdict["year"] = 2019
to traverse the dictionary
You can use for
Traverse the dictionary in a loop.
When traversing the dictionary in a loop, the returned value is the key of the dictionary, but there is also a method to return the value.
Instance
Print all key names in the dictionary one by one:
for x in thisdict: print(x)
Instance
Print all values in the dictionary one by one:
for x in thisdict: print(thisdict[x])
Instance
You can also use values()
The function returns the values of the dictionary:
for x in thisdict.values(): print(x)
Instance
To traverse keys and values using the items() function:
for x, y in thisdict.items(): print(x, y)
Check if the key exists
To determine if a specified key exists in the dictionary, use: in
Keyword:
Instance
Check if "model" exists in the dictionary:
thisdict = { "brand": "Porsche", "model": "911", "year": 1963 } if "model" in thisdict: print("Yes, 'model' is one of the keys in the thisdict dictionary")
Dictionary length
To determine how many items (key-value pairs) are in the dictionary, use: len()
Method.
Instance
Print the number of items in the dictionary:
print(len(thisdict))
Add item
You can add an item to the dictionary by using a new index key and assigning a value to it:
Instance
thisdict = { "brand": "Porsche", "model": "911", "year": 1963 } thisdict["color"] = "red" print(thisdict)
Remove item
There are several ways to remove items from a dictionary:
Instance
The pop() method removes an item with a specified key name:
thisdict = { "brand": "Porsche", "model": "911", "year": 1963 } thisdict.pop("model") print(thisdict)
Instance
popitem()
Method to remove the last inserted item (remove a random item in versions before 3.7):
thisdict = { "brand": "Porsche", "model": "911", "year": 1963 } thisdict.popitem() print(thisdict)
Instance
del thisdict["model"]
thisdict.popitem()
thisdict = { "brand": "Porsche", "model": "911", "year": 1963 } Keyword deletes the item with the specified key name: print(thisdict)
Instance
del thisdict["model"]
del
thisdict = { "brand": "Porsche", "model": "911", "year": 1963 } Keyword can also completely delete the dictionary: del thisdict
Instance
clear()
print(thisdict) #this will cause an error because "thisdict" no longer exists.
thisdict = { "brand": "Porsche", "model": "911", "year": 1963 } Keyword clears the dictionary: print(thisdict)
thisdict.clear()
copy dictionary You cannot copy a dictionary by typing
dict2 = dict1dict2
just to copy the dictionary, because: dict1
will also be automatically reflected in the reference of dict1
Changes in dict2
in.
There are some methods for copying, one of which is to use the built-in dictionary method copy()
.
Instance
Using copy()
Method to copy the dictionary:
thisdict = { "brand": "Porsche", "model": "911", "year": 1963 } mydict = thisdict.copy() print(mydict)
Another way to make a copy is to use the built-in method dict()
.
Instance
Using dict()
Method creates a copy of the dictionary:
thisdict = { "brand": "Porsche", "model": "911", "year": 1963 } mydict = dict(thisdict) print(mydict)
Nested dictionaries
Dictionaries can also contain many dictionaries, which is called nested dictionaries.
Instance
Create a dictionary containing three dictionaries:
myfamily = { "child1" : { "name" : "Phoebe Adele", "year" : 2002 }, "child2" : { "name" : "Jennifer Katharine", "year" : 1996 }, "child3" : { "name" : "Rory John", "year" : 1999 } }
Or, if you want to nest three dictionaries that already exist as dictionaries:
Instance
Create three dictionaries and then create a dictionary containing the other three dictionaries:
child1 = { "name" : "Phoebe Adele", "year" : 2002 } child2 = { "name" : "Jennifer Katharine", "year" : 1996 } child3 = { "name" : "Rory John", "year" : 1999 } myfamily = { "child1" : child1, "child2" : child2, "child3" : child3 }
dict() constructor
You can also use dict()
Constructor creates a new dictionary:
Instance
thisdict = dict(brand="Porsche", model="911", year=1963) # Please note that the keyword is not a string literal # Please note that an equal sign is used instead of a colon for assignment print(thisdict)
Dictionary Methods
Python provides a set of built-in methods that can be used on dictionaries.
Method | Description |
---|---|
clear() | Remove all elements from the dictionary |
copy() | Return a copy of the dictionary |
fromkeys() | Return a dictionary with the specified key and value |
get() | Return the value of the specified key |
items() | Return a list of tuples containing each key-value pair |
keys() | Return a list containing all the keys of the dictionary |
pop() | Delete the element with the specified key |
popitem() | Delete the last inserted key-value pair |
setdefault() | Return the value of the specified key. If the key does not exist, insert a key with the specified value. |
update() | Update the dictionary with the specified key-value pairs |
values() | Return a list of all values in the dictionary |
- Previous Page Python Sets
- Next Page Python If Else