Python DICTionary HowTo » |
My Coding >
Programming language >
Python >
Python DICTionary HowTo
Python DICTionary HowTo (Page: 1)Go to Page: Dictionary in Python is an unsorted collection of key / value pairs. Dictionary in Python ideologically are very similar to hash in Perl How to use dictionary elementThe simplest way is to use value for given key in the dictionary is to call this key in square brakes. But if this key is not existing – then Fatal error will be called:
To avoid this error, you can use method get(), which will give None if the key is absent
Default value for absent elementPretty common task for dictionary – make a counter for objects. For this make a key for every object and increase value accordingly. But the default value for absent key will make this taks a bit easier. Let's consider very simple task – make word popularity in the list.
dictionary with key “word” equal value of “word” + 1 for every new word. But is this key is not existing method .get() return default value “0” and Error is not risen. How to add and remove element to dictionary in PythonHow to Check if a given key already exists in a dictionaryPerform any action with the dictionary with non-existent key will finish with an error. Therefore it is a good idea to check of presence of the key
How to remove element in dictionary by keyRemoving element in dictionary is very simple. You need to know the key of element you would like to delete and use function del()
It is better to check the presence of the key before removal, to make sure that the program will not crash in case of absent key
How to remove element in dictionary by valueTo remove all elements with dictionary with given value, it is easier to use comprehension. In fact we take all pairs from our dictionary and return them back if they values are not equal value prepared for removal
How to compare two dictionariesIt is very easy to compare two dictionaries in Python. Use standard operation == for comparison. Please note, that this comparison is also check case for every string component and also it compare type for every element in dictionary
How to iterate over dictionaryHow to loop over key in dictionaryVery simple and common way of iterations over dictionary is to loop oner key only. In most cases this way of iterations is used
How to loop over key / value in dictionaryFor more complicated cases it is more convenient to have pair key / value in every iterations
But it is necessary to remember, that value is a shallow copy of the dictionary value, therefore:
|
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. |