Python DICTionary HowTo » |
My Coding >
Programming language >
Python >
Python DICTionary HowTo
Python DICTionary HowTo (Page: 2)Go to Page: How to copy two dictionariesIt is possible to create new dictionary identical to already existing by copying. First of all, it is important to know, that if you just use operation = you will copy the reference to the dictionary and then two variables will point to the same dictionary! How to copy reference to dictionaryBy simple copying = you will create the reference to the same objsut, which is not what you usually intend to do Example of potentially WRONG dictionary copy code:
It is possible to see, that by modification of d2 we also modify d1. How to make shallow copy of dictionaryIf the dictionary simple, with one layer of data, then shallow copy will work perfect. It is possible to make shallow copy with dict() and .copy() functions, which are in fact equivalent. If the dictionary have few layers of deepness, then it will produce an error, because shallow copy copies only references from inside the dictionary
How to make deep copy of dictionaryProper full copy of dictionary can be made by copy / deepcopy of the copy module.
For safety it is better to always use deep copy of dictionaries How to merge two dictionaries in PythonThe preferred way of merging to dictionaries is to merge ** of dictionaries. If the keys are overlapped in two dictionaries, then the last value will be used
This techniques can be used for merging of unlimited number of dictionaries
|
Last 10 artitles
9 popular artitles
|
© 2020 MyCoding.uk -My blog about coding and further learning. This blog was writen with pure Perl and front-end output was performed with TemplateToolkit. |