Min menu

Pages

Classes dict in Python

 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.

The concept of class dict in Python At first, dict is an abbreviation for dictionary. Dict is a table consisting of two columns, the first contains the keys (Keys) and the second contains the values ​​(values) of each element. Each element added in dict must be assigned two values. The first represents the key and the second represents its value. Keys are used to access values, so there cannot be two elements in dict with the same key. So, each key is a subject that allows you to access one of the values ​​in 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

Test.py
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.

 
Whether you are defining dict or set, you use the symbol {} as you noticed in the previous example. Therefore, we do not notice any difference between displaying what is contained in dict is empty or set is empty. Once you add one element between the symbol {} and give it a key and a value, then the Python interpreter will understand that you mean to define dict, not set.

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

Test.py
# 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.

{1: 'Admin', 2: 'Editor', 3: 'Reader'}


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

Test.py
# 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.

{'id': 1, 'name': 'saddam', 'phone': 771144276}

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.

To access any element in a dict, whether to get its value, change it or delete it, we use the element's 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

Test.py
# 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.

Admin


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

Test.py
# 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.

Admin


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

Test.py
# 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.

1
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

Test.py
# 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.

Admin
Editor
Reader

Add items inthedictin python

To add a new item inthedictWe pass a new key and then put the value equal to it.

To add a new element in dict, we pass a new key and then put the value it equals.

In the following example, we have defined dictand placed three elements in it.
Then we add a new element to an objectThe dict.

Example

Test.py
# 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.

{1: 'Admin', 2: 'Editor', 3: 'Reader', 4: 'Author'}

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.

To replace the value of any element in the dict, we pass the key of the element whose value we want to exchange, 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

Test.py
# 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.

{1: 'Admin', 2: 'Editor', 3: 'Subscriber'}

How to delete itemsthedictBy sentence delin Python

The sentence delis used to deletethedictAs it is from memory or to delete specific items from it.

The del clause is used to delete a dict as it is from memory, or to delete specific elements from it.

In the first exercise, we defined dictand placed numbers in it. Then we removed two components from it.

First exercise

Test.py
# 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.

{1: 'Admin', 2: 'Editor'}


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

Test.py
# 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.

NameError: name 'data' is not defined

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

Test.py
# 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.

Is Rima in the dict?
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

Test.py
# 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.

3

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.

Clear() function in Python Define it Used to delete all the called dict elements. Built dict.clear () Parameters No parameter is accepted. Return value It does not return a value.

Practical example to understand the working of the () functionclear في بايثون

Test.py
                    # 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.

data contains: {}

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 in Python Define it Returns a copy of the dict that called it. Built dict.copy () Parameters No parameter is accepted. Return value Returns a copy of the dict that called it. Example

Copy() function exercise   

Test.py
                    # 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.

dict1 contains: {1: 'Admin', 2: 'Editor', 3: 'Reader'}
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

Test.py
                    # 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.

Returned element: (3, 'Reader')
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 .

Pop() function in Python Define it It searches in the dict object that called it for the element that has the same key that we pass it on to it in the place of the parameter key and then delete it from it. Built dict.pop (key [, default]) Parameters Place the parameter key We pass the key of the element we want to obtain. The default parameter is an optional parameter, you can pass in its place a default value that will be returned only in case no element was passed that has the key that we to it in place of the key parameter. Return value Returns the item that has been deleted from the dict. Or return the default value passed in place of the parameter default in case no element is found that has the key that we passed to it in place of the parameter key.

First exercise pop

Test.py
                    # 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.

Returned element: (2, 'Editor')
Remaining elements: {1: 'Admin', 3: 'Reader'}


The second example is the pop . function

Test.py
                    # 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.

print('Returned element:', data.pop(5))
KeyError: 5


The third example is the pop . function

Test.py
                    # 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.

Returned element: No item returned
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 

Test.py
                    # 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.

Returned value: Editor


second example function()get 

Test.py
                    # 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.

Returned value: None


The third exercise of the function ( )get 

Test.py
                    # 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.

Returned value: No value found with the specified key

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.

Keys () function in Python Define it An array of type dict_keys returns all the keys in the dict_keys that called it. Note: The key matrix returned is not a copy of the keys in the dict object, but rather the same. Thus, any modification made to the keys from the dict object is reflected in the key matrix and vice versa as well. Built dict.keys () Parameters No parameter is accepted. Return value An array of dict_keys returns in which all the keys in the dict object that he called with noting that this matrix is ​​not a copy of the keys in the dict object, but rather the same. Thus, any modification made to the keys from the dict object is reflected in the key matrix and vice versa as well.

First exercise function()keys 

Test.py
                    # 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.

dict_keys([1, 2, 3])


The second exercise of the function ()keys 

Test.py
                    # 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.

dict_keys([1, 2, 4])

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 

Test.py
                    # 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.

dict_values(['Admin', 'Editor', 'Reader'])


The second exercise of the function ()values 

Test.py
                    # 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.

dict_values(['Admin', 'Editor', 'Subscriber', 'Moderator'])

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

Test.py
                    # 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.

dict_items([(1, 'Admin'), (2, 'Editor'), (3, 'Reader')])


second example function()items

Test.py
                    # 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.

dict_items([(1, 'Admin'), (2, 'Editor'), (3, 'Subscriber'), (4, 'Moderator')])

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 

Test.py
                    # 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.

{1: None, 2: None, 3: None, 4: None}


The second exercise of the function ()fromkeys 

Test.py
                    # 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.

{1: 'Not Specified', 2: 'Not Specified', 3: 'Not Specified', 4: 'Not Specified'}

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 

Test.py
                    # 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.

Returned value: Reader


The second exercise of the function ()setdefaul 

Test.py
                    # 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.

Returned value: None
data contains: {1: 'Admin', 2: 'Editor', 3: 'Reader', 4: None}


The third exercise of the function ( )setdefaul 

Test.py
                    # 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.

Returned value: Subscriber
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

Test.py
                    # 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.

{1: 'Admin', 2: 'Editor', 3: 'Subscriber'}


second exercise

Test.py
                    # 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.

{1: 'Admin', 2: 'Editor', 3: 'Subscriber', 4: 'Moderator'}