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:-

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.

Show Output

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

Show Output

Accessing Objects from a Dictionary

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

Show Output

Nesting Dictionary

Dictionary can also be nested inside another dictionary.

Show Output

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

Close Menu