Python Tutorial
Python Dictionary Methods Explained With Examples
Understanding Dictionary Methods in Python
Python has some built-in methods that you can use in dictionaries.
-
copy()
To return a copy of the dictionary.
Code:
this_dict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x= this_dict.copy()
print(x)
Output:
{'brand': 'Ford', 'model': 'Mustang',’year’:1964}
-
fromkeys()
To return a dictionary with the keys and values supplied.
Code:
x = ('keys1', 'keys2', 'keys3')
y = 1
this_dict = dict.fromkeys(x, y)
print(this_dict)
Output:
['keys1': 1, 'keys2': 1, 'keys3': 1]
-
get()
To return the value of the specified key.
Code:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x= thisdict.copy()
print(x)
Output:
{'brand': 'Ford', 'model': 'Mustang',’year’:1964}
-
items()
The value of the supplied key items is returned.
Code:
y = {
"subject": "python",
"class":”10th",
"year": 2020
}
x = y.get("class")
print(x)
Output:
10th
-
keys()
This returns a list containing the dictionary's keys.
Code:
y = {
"subject": "python",
"class":”10th",
"year": 2020
}
x = y.keys()
print(x)
Output:
dict_keys(['subject', 'class', 'year'])
-
setdefault()
The value of the provided key is returned. If the key doesn't already exist, create it with the supplied value.
Code:
y = {
"subject": "python",
"class":”10th",
"year": 2020
}
x = y.setdefault(“class”,”12th”)
print(x)
Output:
10th
-
update()
The dictionary is updated with the provided key-value pairs.
Code:
y = {
"subject": "python",
"class":”10th",
"year": 2020
}
x = y.update({“color”:”red”})
print(x)
Output:
{ "subject": "python", "class":”10th", "year": 2020 ,“color”:”red” }
-
values()
To return a list of all the values in the dictionary.
Code:
y = {
"subject": "python",
"class":”10th",
"year": 2020
}
x = y.values()
Output:
dict_values(['python', '10th', 2020)
Video : https://youtu.be/SMBw812BLOo
Quiz!
