Dictionary Method

This blogs explains some of the methods available in Python dictionary

clear()

Remove all key value pairs from dictionary

Syntax
dict.clear()

city = {'UK':'London','U.S.A':'Washingtion','India':'Delhi','China':'Beijin'}
print('Dictionary key value pairs')
print(city)
print('Using clear method to remove all pairs from dictionary')
city.clear()
print(city)

Output

Dictionary key value pairs
{'UK': 'London', 'U.S.A': 'Washingtion', 'India': 'Delhi', 'China': 'Beijin'}
Using clear method to remove all pairs from dictionary
{}

get()

Syntax
dict.get(k,r)

Returns value associated with key ‘k’. If no value found, it returns ‘r’

Example

city = {'UK':'London','U.S.A':'Washingtion','India':'Delhi','China':'Beijin'}
print(city.get('UK','Incorrect key'))
print(city.get('France','Incorrect key'))
print(city.get('China','Incorrect key'))
print(city.get('India','Incorrect key'))
print(city.get('Germany','Incorrect key'))

Output

London
Incorrect key
Beijin
Delhi
Incorrect key

items()

Syntax
dict.items()

Returns key value pair for dictionary

Example

city = {'UK':'London','U.S.A':'Washingtion','India':'Delhi','China':'Beijin'}
print(city.items())

Output

dict_items([('UK', 'London'), ('U.S.A', 'Washingtion'), ('India', 'Delhi'), ('China', 'Beijin')])

keys()

Syntax
dict.keys()

Returns only keys from the dictionary

Example

city = {'UK':'London','U.S.A':'Washingtion','India':'Delhi','China':'Beijin'}
print(city.keys())

Output

dict_keys(['UK', 'U.S.A', 'India', 'China'])

values()

Syntax
dict.values()

Returns only values from dictionary

Example

city = {'UK':'London','U.S.A':'Washingtion','India':'Delhi','China':'Beijin'}
print(city.values())

Output

dict_values(['London', 'Washingtion', 'Delhi', 'Beijin'])

update()

Syntax
dict1.update(dict2)

Copies all key-value pairs from dict2 to dict1

Example

city = {'UK':'London','U.S.A':'Washingtion','India':'Delhi','China':'Beijin'}
city2 = {'France':'Paris','Germany':'Berlin','Japan':'Tokyo','Egypt':'Cairo'}
city.update(city2)
print(city)

Output

{'UK': 'London', 'U.S.A': 'Washingtion', 'India': 'Delhi', 'China': 'Beijin', 'France': 'Paris', 'Germany': 'Berlin', 'Japan': 'Tokyo', 'Egypt': 'Cairo'}
Advertisement

Leave a Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s