Thursday, March 1, 2018

Dictionary Methods in python programming language

clear
The clear method removes all items from the dictionary. This is an in-place operation (like
list.sort), so it returns nothing (or, rather, None):
>>> d = {}
>>> d['name'] = 'Gumby'
>>> d['age'] = 42
>>> d
{'age': 42, 'name': 'Gumby'}
>>> returned_value = d.clear()
>>> d
{}
>>> print returned_value
None

copy
The copy method returns a new dictionary with the same key-value pairs (a shallow copy, since
the values themselves are the same, not copies):
>>> x = {'username': 'admin', 'machines': ['foo', 'bar', 'baz']}
>>> y = x.copy()
>>> y['username'] = 'mlh'
>>> y['machines'].remove('bar')
>>> y
{'username': 'mlh', 'machines': ['foo', 'baz']}
>>> x
{'username': 'admin', 'machines': ['foo', 'baz']}

fromkeys
The fromkeys method creates a new dictionary with the given keys, each with a default corresponding
value of None:
>>> {}.fromkeys(['name', 'age'])
{'age': None, 'name': None}
>>> dict.fromkeys(['name', 'age'])
{'age': None, 'name': None}

get
The get method is a forgiving way of accessing dictionary items. Ordinarily, when you try to
access an item that is not present in the dictionary, things go very wrong:
>>> d = {}
>>> print d['name']
Traceback (most recent call last):
File "<stdin>", line 1, in ?
KeyError: 'name'
 >>> print d.get('name')
    None
>>> d['name'] = 'Eric'
>>> d.get('name')
'Eric'

has_key

The has_key method checks whether a dictionary has a given key
>>> d = {}
>>> d.has_key('name')
False
>>> d['name'] = 'Eric'
>>> d.has_key('name')
True

update
The update method updates one dictionary with the items of another:
>>> d = {
'title': 'Python Web Site',
'url': 'http://www.python.org',
'changed': 'Mar 14 22:09:15 MET 2008'
}
>>> x = {'title': 'Python Language Website'}
>>> d.update(x)
>>> d
{'url': 'http://www.python.org', 'changed':
'Mar 14 22:09:15 MET 2008', 'title': 'Python Language Website'}

setdefault
The setdefault method is somewhat similar to get, in that it retrieves a value associated with
a given key.
>>> d = {}
>>> d.setdefault('name', 'N/A')
'N/A'
>>> d
{'name': 'N/A'}
>>> d['name'] = 'Gumby'
>>> d.setdefault('name', 'N/A')
'Gumby'
>>> d
{'name': 'Gumby'}

popitem
The popitem method is similar to list.pop, which pops off the last element of a list. Unlike
list.pop, however, popitem pops off an arbitrary item because dictionaries don’t have a “last
element” or any order whatsoever. This may be very useful if you want to remove and process
the items one by one in an efficient way (without retrieving a list of the keys first):
>>> d
{'url': 'http://www.python.org', 'spam': 0, 'title': 'Python Web Site'}
>>> d.popitem()
('url', 'http://www.python.org')
>>> d
{'spam': 0, 'title': 'Python Web Site'}

pop
The pop method can be used to get the value corresponding to a given key, and then remove the
key-value pair from the dictionary:
>>> d = {'x': 1, 'y': 2}
>>> d.pop('x')
1
>>> d
{'y': 2}

0 comments:

Post a Comment