Python - Dictionary
Python
Built-in Data Structure -- Dictionary
1. Dictionary items are ordered, changeable,
and does not allow duplicates.
2. Dictionary items are presented in
key:value pairs, and can be referred to by using the key name.
3. Dictionary items are mutable.
4. Dictionary are iterable.
Dictionary
Methods
It has total of 11 methods.
Clear
() – It’s used to remove all the items from the
dictionary.
Copy () – It’s used to return the copies of the given dictionary.
Keys () - The keys () method returns a view object. The view object contains the keys of the dictionary, as a list. The view object will reflect any changes done to the dictionary.
Values () - The values () method returns a view object. The view object contains the values of the dictionary, as a list. The view object will reflect any changes done to the dictionary.
Items () – The items () method returns a view object. The view object contains the key-value pair of dictionary, as a tuples in a list. The view object will reflect any changes done to the dictionary.
Pop () – It is used to remove the specified item from the dictionary. In pop method argument provide the key name which item you want to pop from the dictionary. If the key is not existing in the dictionary than an error is raised.
- It’s generated an error. But if you want that the error should be user specific you can provide optional argument.
- dictionary.pop(keyname, defaultvalue) Default value is optional.
Popitem () – It’s used to removes the last inserted key-value pair.
Get () - The get () method returns the value of the item with the specified key.
- If the value doesn’t exist it’s returns the NONE. Means no error.
- But, If you passed the second argument it will return that value. Instead of None.
Fromkeys
() – It’s
used to returns a dictionary with the specified keys and value. Value is
optional here. Default Value is NONE.
Syntax - dict.fromkeys(keys, value) # keys is any iterable.
Update () - The update
() method inserts the specified items to the dictionary.
The specified items can be a dictionary, or an iterable object with key value pairs.
setdefault () -
The setdefault() method
returns the value of the item with the specified key.
If the key does not exist, insert the key, with the specified
value.
Questions
Que - How to create an empty dictionary?
Ans - dictionary_variable = {}
Que - Create a dictionary with integer keys?
Ans - a = {1:"hello,2:"world"}
Que - How to delete the dictionary?
Ans - del dictionary_variable
Que -Explain setdefault () method?
Ans - It means if the key exist it will return the value of the key. but if key doesn't exist it will add the same key into the dictionary and give the value as NONE. If we didn't mention the value.
Comments
Post a Comment