Python OOPs


Python SQLite


Examples


Others


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.

copy() Method

info={'name':'Tom','age':28}
b=info.copy()
print(b)
Output
{'name': 'Tom', 'age': 28}

clear() Method

info={'name':'Tom','age':28}
info.clear()
print(info)
Output
{}

fromkeys() Method

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)
Output
{'a': 0, 'e': 1, 'i': 0, 'o': 1, 'u': 1}

get() Method

info={'name':'Tom','age':28,'contact':'9876543210'}
cont=info.get('contact')
print(cont)
Output
9876543210

items() Method

info={'name':'Tom','age':28,'contact':'9876543210'}
a=info.items()
print(a)
Output
dict_items([('name', 'Tom'), ('age', 28), ('contact', '9876543210')])

pop() Method

info={'name':'Tom','age':28,'contact':'9876543210'}
info.pop('age')
print(info)
Output
{'name': 'Tom', 'contact': '9876543210'}

popitem() Method

info={'name':'Tom','age':28,'contact':'9876543210'}
info.popitem()
print(info)
Output
{'name': 'Tom', 'age': 28}

setdefault() Method

info={'name':'Tom','age':28,'contact':'9876543210'}
info.setdefault('age',30)
info.setdefault('city','salem')
print(info)
Output
{'name': 'Tom', 'age': 28, 'contact': '9876543210', 'city': 'salem'}

update() Method

info={'name':'Tom','age':28,'contact':'9876543210'}
info.update({'age':30})
print(info)
Output
{'name': 'Tom', 'age': 30, 'contact': '9876543210'}

keys() Method

info={'name':'Tom','age':28,'contact':'9876543210'}
print(info.keys())
Output
dict_keys(['name', 'age', 'contact'])

values() Method

info={'name':'Tom','age':28,'contact':'9876543210'}
print(info.values())
Output
dict_values(['Tom', 28, '9876543210'])