Python Dictionaries
Python Dictionaries
Python has a data structure called Dict in which you can store value with key: pair combination. e.g., dict= {key1: value1, key2 : value2,…… }. The “empty dict” is just an empty pair of curly braces {}.
Looking up or setting a value in a dict uses square brackets. eg., dict[‘code’] looks up the value under the key ‘code’. Strings, numbers, and tuples work as keys, and any type can be a value. Looking up a value which is not in the dict throws a KeyError — use “in” to check if the key is in the dict, or use dict.get(key) which returns the value or None if the key is not present (or get(key, not-found) allows you to specify what value to return in the not-found case).
We can also run a for loop on dict to iterate through all of the keys. There are two methods dict.key() and dict.values() returns the list of the keys or values respectively. Another function dict.items() returns the list of (key,value) tuple.
Delete
The “del” operator does deletions. In the simplest case, it can remove the definition of a variable, as if that variable had not been defined. Del can also be used on list elements or slices to delete that part of the list and to delete entries from a dictionary.
So, that covers the basic of dictionaries in python.
So be connected. Thanks for visiting. Share this with your friends.
Comment your suggestions.
Leave a comment