Classes dictin Python
In the beginning, an dictacronym fordictionaryWhich means dictionary or glossary.
thedictIt is a table consisting of two columns, the first contains the keys(Keys)The second contains the values(Values)specific to each element.
Each item added in dictmust be given two values. The first is the key(Key)The second represents its value(Value).
Keys are used to access values, so there can be no two elements inthedictThey have the same key. So, allKeyA topic that allows you to access one of the values inThe dict.
method of definitiondict in python
To define dictwe use the symbol .{ }.
Inside this code, you can pass elements directly to it, provided that you put a comma between every two elements.
Don't forget that each element must have two values, the first representing the key and the second representing the value. Between each key and value we put the symbol:.
In the next exercise we have defined dictempty, that is, it does not contain any element.
First exercise
alawiri = {} # empty alawiri named dict here you defined
print(alawiri) # (that is, as we defined it) as data Here we have shown what the object contains
• We will get the following outputs upon implementation.
Whether you are defining dictor setyou are using symbol { }as you noted in the previous example.
Therefore, we do not notice any difference between displaying dictempty or empty content set.
Once you add one element between the code { }and give it a key and a value, then the Python interpreter will understand that you mean a definition dict, notset.
In the following exercise, we have defined dictour situation with three elements.
The keys we put as numbers, and the values we put as text with the indication that you can put any type you want.
We also defined each element(that is, every key and value)On a single line just to make it easier to read.
second example
# alawiri consists of three elements, its name is dict here I have defined
alawiri = {
1: 'Admin',
2: 'Editor',
3: 'Reader'
}
# (that is, as we defined it) as alawiri here we have shown what the object contains
print(alawiri)
• We will get the following result when running.
In the following exercise, we have defined dictour situation with three elements.
Keys are set as text, and values are set as numbers and text.
The third exercise
# mydata consists of three elements, its name is dict here I have defined
mydata = {
'id': 1,
'name': 'saddam',
'phone': 771144276
}
# (that is, as we defined it) as mydata here we have shown what the object contains
print(mydata)
• We will get the following result when running.
How to access element values?thedictin python
To access any item inthedictWhether to get, change, or delete its value we use the element's private key.
In the first exercise, we defined dictand placed three elements in it, then we used the symbol []to display the value of the element that has the key number1 .
First exercise
# data consists of three elements, its name is dict. Here we have defined
data = {
1: 'Admin',
2: 'Editor',
3: 'Reader'
}
#1 Here we have printed the value of the element that has the key number
print(data[1])
• We will get the following result when running.
In the second exercise, we defined dictand placed three elements in it, then we used the function get()to display the value of the element that has the key number1 .
second exercise
# data consists of three elements, its name is dict. Here we have defined
data = {
1: 'Admin',
2: 'Editor',
3: 'Reader'
}
#1 Here we have printed the value of the element that has the key number
print(data.get(1))
• We will get the following result when running.
In the third example, we defined dictand placed three elements in it, then we displayed all keys placed in it using the loopfor.
The third exercise
# data consists of three elements, its name is dict. Here we have defined
data = {
1: 'Admin',
2: 'Editor',
3: 'Reader'
}
# and then it will print the key in the data variable every time the key of an element of the object will be placed
for key in data:
print(key)
• We will get the following result when running.
2
3
In the fourth exercise, we defined dictand placed three elements in it, then we displayed all the keys placed in it using the loopfor.
Fourth exercise
# data consists of three elements, its name is dict. Here we have defined
data = {
1: 'Admin',
2: 'Editor',
3: 'Reader'
}
# Then the value of this key will be printed in the data variable every time the key of an element of the object is placed
for key in data:
print(data[key])
• We will get the following result when running.
Editor
Reader
Add items inthedictin python
To add a new item inthedictWe pass a new key and then put the value equal to it.
In the following example, we have defined dictand placed three elements in it.
Then we add a new element to an objectThe dict.
Example
# data consists of three elements, its name is dict. Here we have defined
data = {
1: 'Admin',
2: 'Editor',
3: 'Reader'
}
# 'Author' has a key number 4, and its value is text, data here we have added a new element in the object
data[4] = 'Author'
# data Here we have shown what the object has become
print(data)
• We will get the following result when running.
Toggle element valuesthedictin python
To toggle the value of any item inthedictWe pass the key of the element whose value we want to change, and then we put the new value.
In the following example, we have defined dictand placed three elements in it.
Then we replace the value of the element that has a key equal to3 .
Example
# data consists of three elements, its name is dict. Here we have defined
data = {
1: 'Admin',
2: 'Editor',
3: 'Reader'
}
# 'Subscriber' we put in its place the text .data here we switched the value of the element that has the key number 3 in the object
data[3] = 'Subscriber'
# data Here we have shown what the object has become
print(data)
• We will get the following result when running.
How to delete itemsthedictBy sentence delin Python
The sentence delis used to deletethedictAs it is from memory or to delete specific items from it.
In the first exercise, we defined dictand placed numbers in it. Then we removed two components from it.
First exercise
# data consists of three elements, its name is dict. Here we have defined
data = {
1: 'Admin',
2: 'Editor',
3: 'Reader'
}
# data Here we have deleted the element that has key number 3 in the object
del data[3]
# data Here we have shown what the object has become
print(data)
• We will get the following result when running.
In the second exercise we made a definition dictconsisting of three elements. Then we deleted it from memory. Then we tried to show what it contains.
second exercise
# data consists of three elements, its name is dict. Here we have defined
data = {
1: 'Admin',
2: 'Editor',
3: 'Reader'
}
# As it is from memory data Here we have deleted the object
del data
# which we originally deleted from memory so an error will appear when we run data here we tried to display what the object contains
print(data)
• We will get the following result when running.
way to know ifthedictContains a specific key in Python
The operator inis used to search inthedictFor a specific key or to pass its values when used in a loop, foras we did in some of the previous examples.
When using the operator into search inthedictFor a key it returns Trueif an element with that key is found.
It returns Falseif it does not find an item that has this key.
In the following exercise, we used the operator into search forthedictfor an element that has a key equal to2 .
exercise
# data consists of three elements, its name is dict. Here we have defined
data = {
1: 'Admin',
2: 'Editor',
3: 'Reader'
}
# True for key number 2. If an object with this key is found, data will be displayed here. The object will be searched
print(2 in data)
• We will get the following result when running.
True
How to find out the number of elementsthedictin python
To find out the number of elements of an object of its type dictwe use the functionlen().
In the following exercise, we have a definition dictconsisting of three components. Then we print the number of its elements using the functionlen().
An exercise explaining the function() clear in Python
# data consists of three elements, its name is dict. Here we have defined
data = {
1: 'Admin',
2: 'Editor',
3: 'Reader'
}
# len() that the data function will return here we have shown the number of elements of the object
print(len(data))
• We will get the following result when running.
Python Explanation of Class Functions dictin Python
The() function is used to clear لdelete all elementsthedictwho summoned her.
function body()clear يكون بالشكل التالي
dict.clear()
The () function clear does not accept any parameter.
The function() clear does not return a value.
Practical example to understand the working of the () functionclear في بايثون
# data consists of three elements, its name is dict. Here we have defined
data = {
1: 'Admin',
2: 'Editor',
3: 'Reader'
}
# data Here we have deleted all the elements in the object
data.clear()
# Empty dict which will appear as data Here we have shown what the object contains
print('data contains:', data)
• We will get the following output when running.
Explanation of the function() copy in Python
Return a copy ofthedictwho summoned her.
The body and structure of the Copy() function is as follows
dict.copy()
The Copy() function does not accept any parameter and returns a copy ofthedictwho summoned her.
Copy() function exercise
# data1 consists of three elements, its name is dict. Here we have defined
data1 = {
1: 'Admin',
2: 'Editor',
3: 'Reader'
}
# data2 in the data1 object here we have copied the objects of the object
data2 = data1.copy()
# data2 and data1 here we have shown what the object contains
print('dict1 contains:', data1)
print('dict2 contains:', data2)
• We will get the following output when running.
dict2 contains: {1: 'Admin', 2: 'Editor', 3: 'Reader'}
Explanation of the function() popitem in Python
Returns the last element added in an objectthedictWho summoned it and then deleted it.
function body popitem
dict.popitem()
Do not accept any parameters and return the item that was deleted fromThe dict.
function popitem . errors
Throws the Exception KeyError if it isthedictEmpty.
popitem function exercise
# data consists of three elements, its name is dict. Here we have defined
data = {
1: 'Admin',
2: 'Editor',
3: 'Reader'
}
# and display its value data here we extracted the last element in the object
print('Returned element:', data.popitem())
# data Here we have displayed the remaining elements in the object
print('Remaining elements:', data)
• We will get the following output when running.
Remaining elements: {1: 'Admin', 2: 'Editor'}
Explanation of the function() pop in Python
looking at an objectthedictWhich called it for the element that has the same key that we pass it to it in place of the parameter keyand then delete it from it.
The body of the function pop
dict.pop(key[, default])
Pop . function parameters
The location of the parameter
keyWe pass the key of the element we want to get.The parameter
defaultis an optional parameter, you can pass in its place a default value that is returned only if an element with the key we passed to it is not found in the parameter's placekey.
The pop function returns the element that was deleted fromThe dict.
Or, return the default value passed in the parameter default's place if no element with the key we passed has been found in the parameter's place.key.
Possible errors in the pop . function
If the key to be deleted is not found, and the parameter location value is not passed to it, an defaultexception is thrownKeyError .
First exercise pop
# data consists of three elements, its name is dict. Here we have defined
data = {
1: 'Admin',
2: 'Editor',
3: 'Reader'
}
# And then we displayed it as data here we extracted the element that has key number 2 from the object
print('Returned element:', data.pop(2))
# data Here we have displayed the remaining elements in the object
print('Remaining elements:', data)
• We will get the following output when running.
Remaining elements: {1: 'Admin', 3: 'Reader'}
The second example is the pop . function
# data consists of three elements, its name is dict. Here we have defined
data = {
1: 'Admin',
2: 'Editor',
3: 'Reader'
}
# And then we displayed it as data here we tried to extract the element that has key number 5 from the object
# Since no element has a key equal to the number 5, an error will be shown when the program is run
print('Returned element:', data.pop(5))
# data Here we have displayed the remaining elements in the object
print('Remaining elements:', data)
• We will get the following output when running.
KeyError: 5
The third example is the pop . function
# data consists of three elements, its name is dict. Here we have defined
data = {
1: 'Admin',
2: 'Editor',
3: 'Reader'
}
# And then we displayed it as data here we tried to extract the element that has key number 5 from the object
# Since no element has a key equal to 5 and there is a default value, the default value will be returned
print('Returned element:', data.pop(5, 'No item returned'))
# data Here we have displayed the remaining elements in the object
print('Remaining elements:', data)
• We will get the following output when running.
Remaining elements: {1: 'Admin', 2: 'Editor', 3: 'Reader'}
Python Explanation of the function() get in Python
The() function get searches an objectthedictWhich calls it about the value of the key we pass to it in place of the parameter keyand returns it.
function()get لها الشكل التالي
dict.get(key[, default])
function parameters()get
The location of the parameter
keyWe pass the key of the element whose value we want to get.The parameter
defaultis an optional parameter, you can pass in its place a default value that is returned only if an element with the key we passed to it is not found in the parameter's placekey.
The function() get returns the value of the key to be searched inthedictIf an item is found that has the key.
Returns Noneif an element with the key was not found and we did not pass it a default value.
If a default value is passed to it and an element with the key whose value is to be obtained is not found, it returns the default value.
First exercise function()get
# data consists of three elements, its name is dict. Here we have defined
data = {
1: 'Admin',
2: 'Editor',
3: 'Reader'
}
# Then we display it, here we get the value of the element that has key number 2 from the object
print('Returned value:', data.get(2))
• We will get the following output when running.
second example function()get
# data consists of three elements, its name is dict. Here we have defined
data = {
1: 'Admin',
2: 'Editor',
3: 'Reader'
}
# And then we display it, here we try to get the value of the element that has key number 5 from the object
# Since no element has a key equal to the number 5, an error will be shown when the program is run
print('Returned value:', data.get(5))
• We will get the following output when running.
The third exercise of the function ( )get
# data consists of three elements, its name is dict. Here we have defined
data = {
1: 'Admin',
2: 'Editor',
3: 'Reader'
}
# And then we display it, here we try to get the value of the element that has key number 5 from the object
# Since no element has a key equal to 5 and there is a default value, the default value will be returned
print('Returned value:', data.get(5, 'No value found with the specified key'))
• We will get the following output when running.
Explanation of the function() keys in Python
The function() keys returns an array of typedict_keyscontaining all the keys in an objectthedictwho summoned her.
Important : The key array returned, is not a copy of the keys in an objectthedictRather it is the same. Thus any modification made to the keys of an objectthedictIt is reflected in the matrix of keys and vice versa.
function()keys لها الشكل التالي
dict.keys()
The function() keys لا accepts any parameter.
The function() keys returns an array of its type dict_keyscontaining all the keys in an objectthedictwho called it indicating that this array is not a copy of the keys in an objectthedictRather it is the same. Thus any modification made to the keys of an objectthedictIt is reflected in the matrix of keys and vice versa.
First exercise function()keys
# data consists of three elements, its name is dict. Here we have defined
data = {
1: 'Admin',
2: 'Editor',
3: 'Reader'
}
# keys In the keys() object that the dict_keys function will return here we have stored the object
keys = data.keys()
# As is keys here we have shown what the object contains
print(keys)
• We will get the following output when running.
The second exercise of the function ()keys
# data consists of three elements, its name is dict. Here we have defined
data = {
1: 'Admin',
2: 'Editor',
3: 'Reader'
}
# keys In the keys() object that the dict_keys function will return here we have stored the object
keys = data.keys()
# data Here we have deleted the element with key number 3 from the object
data.pop(3)
# data Here we have added a new element to the object
data[4] = 'Moderator'
# keys are also applied to the data object as is. Notice that all the changes we made to the keys object here show what the object contains
print(keys)
• We will get the following output when running.
Explanation of the function() values in Python
function()values returns an array of type dict_valuescontaining all the values in an objectthedictwho summoned her.
Important: The array of values returned, is not a copy of the values in an objectthedictRather it is the same. Hence any modification made to the values of an objectthedictIt is reflected in the matrix of values and vice versa.
function()values لها الشكل التالي
dict.values()
The () function values does not accept any parameter.
The function() values returns an array of type dict_valuescontaining all the values in an objectthedictwhich called it indicating that this array is not a copy of the values in an objectthedictRather it is the same. Hence any modification made to the values of an objectthedictIt is reflected in the matrix of values and vice versa.
First exercise function()values
# data consists of three elements, its name is dict. Here we have defined
data = {
1: 'Admin',
2: 'Editor',
3: 'Reader'
}
# values in the values() object which the dict_values function will return here we have stored the object
values = data.values()
# As values here we have shown what the object contains
print(values)
• We will get the following outputs upon implementation.
The second exercise of the function ()values
# data consists of three elements, its name is dict. Here we have defined
data = {
1: 'Admin',
2: 'Editor',
3: 'Reader'
}
# values in the values() object which the dict_values function will return here we have stored the object
values = data.values()
# data Here we have changed the value of the element that has key number 3 in the object
data[3] = 'Subscriber'
# data Here we have added a new element to the object
data[4] = 'Moderator'
# values are also applied to the data object as is. Notice that all the changes we made to the values object here show what the object contains
print(values)
• We will get the following output when executed.
Python Explanation of the function() items in Python
function()items returns an array of type dict_itemscontaining all the elements in an objectthedictwho summoned her.
Important : The array of elements returned is not a copy of the elements in an objectthedictRather it is the same. Thus any modification made to the elements of an objectthedictIt is reflected in the matrix of elements and vice versa.
function()items لها الشكل التالي
dict.items()
The () function items does not accept any parameter.
The () function items returns an array of type dict_itemscontaining all the elements in an objectthedictwho invokes it indicating that this array is not a copy of the elements in an objectthedictRather it is the same. Thus any modification made to the elements of an objectthedictIt is reflected in the matrix of elements and vice versa.
First exercise function()items
# data consists of three elements, its name is dict. Here we have defined
data = {
1: 'Admin',
2: 'Editor',
3: 'Reader'
}
# items in the items() object that the dict_items function will return here we have stored the object
items = data.items()
# as items here we have shown what the object contains
print(items)
• We will get the following result when running.
second example function()items
# data consists of three elements, its name is dict. Here we have defined
data = {
1: 'Admin',
2: 'Editor',
3: 'Reader'
}
# items in the items() object that the dict_items function will return here we have stored the object
items = data.items()
# data Here we have changed the value of the element that has key number 3 in the object
data[3] = 'Subscriber'
# data Here we have added a new element to the object
data[4] = 'Moderator'
# items are also applied to the data object as is. Notice that all the changes we made to the items object here show what the items contain
print(items)
• We will get the following outputs upon implementation.
Python Explanation of the function() fromkeys in Python
The() function is used fromkeys to create dicta new one based on the values of an array that we pass to it.
When called, we pass an object representing an array of any type where the parameter isseq,Elements of this object are placed as keys in an objectthedictwhich will be returned.
The location of the parameter valueYou can pass the default value you want to set to all the elements of an objectthedictwhich will be returned.
And if you do not pass a default value in place of the parameter value, all values will be equal toNone.
The function() fromkeys has the following
dict.fromkeys(seq[, value])
function parameters()fromkeys
In place of the parameter
seqwe pass an array of any type.The parameter
valueis an optional parameter, you can pass in its place a default value to be set to all elements of an objectthedictwhich will be returned.
The () function fromkeys returns dictnew.
First example function()fromkeys
# consists of 4 tuple elements here we have defined aTuple = (1, 2, 3, 4) # None and we didn't set its default value so they will all be equal to a new aTuple whose keys are the values in the dict object here we created an object aDict = dict.fromkeys(aTuple) # aDict Here we have shown what the object contains print(aDict)
• We will get the following result when running.
The second exercise of the function ()fromkeys
# consists of 4 tuple elements here we have defined aTuple = (1, 2, 3, 4) # 'Not Specified' and the default value of all its elements is the text a new aTuple whose keys are the values in the dict object Here we have created an object aDict = dict.fromkeys(aTuple, 'Not Specified') # aDict Here we have shown what the object contains print(aDict)
• We will get the following result when running.
Function() setdefaul in Python
The() function is used setdefaul to get the value of a key contained in an objectthedictThe one who called it, or to add a new item in it and return its value as well.
The location of the parameter keywe pass the key of the element that if it exists in an objectthedictOnly its value will be returned, and if it is not present, it will be added and its value returned.
The location of the parameter default. You can pass the default value that you want to put to the element in case it is added because by default if a new element is added, its value will beNone.
function body()setdefaul
dict.setdefault(key[, default])
function parameters()setdefaul
The location of the parameter
keywe pass the key of the element that if it exists in an objectthedictOnly its value will be returned, and if it is not present, it will be added and its value returned.The parameter
defaultis an optional parameter, you can pass in its place the default value that you want to put in the element in case it is to be added.
The function() setdefaul returns the value of the key passed to it in the place of the parameterkey.
First exercise function()setdefaul
# data consists of three elements, its name is dict. Here we have defined
data = {
1: 'Admin',
2: 'Editor',
3: 'Reader'
}
# Then we display it, here we get the value of the element that has key number 3 from the object
print('Returned value:', data.setdefault(3))
• We will get the following result when running.
The second exercise of the function ()setdefaul
# data consists of three elements, its name is dict. Here we have defined
data = {
1: 'Admin',
2: 'Editor',
3: 'Reader'
}
# And then we display it, here we try to get the value of the element that has key number 4 from the object
# None has a key of 4 and a value of data Since there is no element with a key equal to 4, a new element will be added to the object
print('Returned value:', data.setdefault(4))
# data Here we have displayed all the elements in the object
print('data contains:', data)
• We will get the following result when running.
data contains: {1: 'Admin', 2: 'Editor', 3: 'Reader', 4: None}
The third exercise of the function ( )setdefaul
# data consists of three elements, its name is dict. Here we have defined
data = {
1: 'Admin',
2: 'Editor',
3: 'Reader'
}
# And then we display it, here we try to get the value of the element that has key number 4 from the object
# 'Subscriber' has a key of 4 and the value of text is data Since no element has a key equal to 4, a new element will be added to the object
print('Returned value:', data.setdefault(4, 'Subscriber'))
# data Here we have displayed all the elements in the object
print('data contains:', data)
• We will get the following result when running.
data contains: {1: 'Admin', 2: 'Editor', 3: 'Reader', 4: 'Subscriber'}
Explanation of the function() update in Python
The update function is used to update the values of an elementthedictWho called it based on the keys in it.
The body of the update function is as follows
dict.update([other])
The update function has an optional parameter, the other parameter.dictthedictwho summoned her.
Which element do we pass in place of the parameter?other has a key that is not in an objectthedictThe one who called it will be added to it. Returns None if no error occurs.
First exercise
# data consists of three elements, its name is dict. Here we have defined
data = {
1: 'Admin',
2: 'Editor',
3: 'Reader'
}
# data Here we have updated the value of the element that has key number 3 in the object
data.update({3: 'Subscriber'})
# data Here we have displayed all the objects of the object
print(data)
• We will get the following result when running.
second exercise
# data consists of three elements, its name is dict. Here we have defined
data = {
1: 'Admin',
2: 'Editor',
3: 'Reader'
}
# And add a new element because there is no element that has a key equal to 4 data here we have updated the value of the element that has the key number 3 in the object
data.update({
3: 'Subscriber',
4: 'Moderator'
})
# data Here we have displayed all the objects of the object
print(data)
• We will get the following result when running.