Dictionary in python is mapping. It consists of a key and an associated value.

Mapping is a collection of objects that are stored by a key.

syntax:-

d = {'key1': 'value1', 'key2' : 'value2′', 'key3' : 'value3'}

Characteristics:-

  • Data type to store more than one value in one variable name.
  • Dictionary items are stored in curly brackets { }.
  • Dictionary items consist of key and value.
  • Items in dictionary are separated by using comma.
  • It doesn’t follow any order unlike list and can appear randomly.

Construction of a Dictionary

Dictionary in python can be created directly providing keys and values at the time of declaration.

#create dictionary of three keys
mobile={'android':'samsung', 'model':'pro7', 'price':'7990'}
print(mobile)

Output

{'price': '7990', 'android': 'samsung', 'model': 'pro7'}

Dictionary can also be cronstructed as empty and can add items later.

d = {}
print(d)

#add item in dictionary
d['lang'] = 'Python'
print(d)

Output

{}

{'lang': 'Python'}

Accessing Objects from a Dictionary

To access any value in the dictionary use its corresponding key as a subscript.

mobile={'android':'samsung', 'model':'pro7', 'price':'7990'}

#access element from dictionary
price = mobile['price']
print(price)

Output

7990

Nesting Dictionary

Dictionary can also be nested inside another dictionary.

animal = {'breath': 'true', 'dog':{'legs': 4} }

print(animal)
print(animal['dog'])

Output

{'breath': 'true', 'dog': {'legs': 4}}
{'legs': 4}

Basic Dictionary Methods

  • update({‘key’: ‘new_value’}) – Update the current ‘value’ of ‘key’ with ‘new_value’.
  • get(‘key’) – Returns the value corresponding to the ‘key’.
  • items() – Returns dictionary as list of tuples.
  • pop(‘key’) – Removes the key:value pair from the dictionary.
  • keys() – Returns list of keys present in the dictionary.
  • values() – Returns list of values present in the dictionary.
  • clear() – Empties the dictionary.

Leave a Reply