Python Dictionary Methods
Python Dictionary is used to store data in a key-value pairs. Dictionary is an unordered collection of objects, which is changeable and does not allow duplicate keys.
Method | Description |
---|---|
copy() | Used to return copy of the dictionary. |
clear() | Removes all the elements from the dictionary. |
fromkeys() | Used to create a dictionary with the specified keys and value. |
get() | Used to get value of the specified key. |
items() | Used to return a list containing a tuple of each key value pair. |
pop() | Used to remove the element with the given key. |
popitem() | Used to remove the last key value pair. |
setdefault() | Used to insert key with a value if key not exsist. |
update() | Used to Update the Dictionary. |
keys() | Used to return a list of all the keys in the dictionary. |
values() | Used to return a list of all the values in the dictionary. |
info={'name':'Tom','age':28} b=info.copy() print(b)
{'name': 'Tom', 'age': 28}
info={'name':'Tom','age':28} info.clear() print(info)
{}
keys=('a','e','i','o','u') value=0 vowel_count=dict.fromkeys(keys,value) for x in 'Computer': if x in keys: vowel_count[x]+=1 print(vowel_count)
{'a': 0, 'e': 1, 'i': 0, 'o': 1, 'u': 1}
info={'name':'Tom','age':28,'contact':'9876543210'} cont=info.get('contact') print(cont)
9876543210
info={'name':'Tom','age':28,'contact':'9876543210'} a=info.items() print(a)
dict_items([('name', 'Tom'), ('age', 28), ('contact', '9876543210')])
info={'name':'Tom','age':28,'contact':'9876543210'} info.pop('age') print(info)
{'name': 'Tom', 'contact': '9876543210'}
info={'name':'Tom','age':28,'contact':'9876543210'} info.popitem() print(info)
{'name': 'Tom', 'age': 28}
info={'name':'Tom','age':28,'contact':'9876543210'} info.setdefault('age',30) info.setdefault('city','salem') print(info)
{'name': 'Tom', 'age': 28, 'contact': '9876543210', 'city': 'salem'}
info={'name':'Tom','age':28,'contact':'9876543210'} info.update({'age':30}) print(info)
{'name': 'Tom', 'age': 30, 'contact': '9876543210'}
info={'name':'Tom','age':28,'contact':'9876543210'} print(info.keys())
dict_keys(['name', 'age', 'contact'])
info={'name':'Tom','age':28,'contact':'9876543210'} print(info.values())
dict_values(['Tom', 28, '9876543210'])