What is dictionary?
- A dictionary is an ordered collection.
- Dictionary is Mutable(changeable).
- Dictionary elements are key-value pairs.
- A Dictionary in python is declared by enclosing a comma-separated list of key-value pairs using curly braces(“{}”).
- Key: Keys is an object and single value.
- Values: Values can be a list or nested list, numbers, etc.
- That means more than one element will be present in values
- Set stores the elements directly
- set = {ele1 , ele2 , ele3 ….}
- While the Dictionary stores elements using keys.
- dict = {key : ele , key : ele , key : ele }
Differences between List, Set and Dictionary:
- List, Set and Dictionary are Mutable objects
- List can store Mutable and Immutable objects
- Set can store only Immutable objects
- Dictionary Keys must be Immutable where as Values can be Mutable or Immutable.
- List and Dictionary objects are ordered collections
- Set is not ordered.
- List can be used to work with simple set of objects.
- Dictionary is used to work with set of duplicate elements with unique keys
Dictionary is an ordered collection.
emp = {101:"amar", 102:"annie", 103:"hareen"}
print("Dictionary :", emp)
Output:
Dictionary : {101: 'amar', 102: 'annie', 103: 'hareen'}
- Elements can be heterogeneous.
- Keys can be heterogeneous
d = {10:"abc", "xyz":2.34, 1.23:None}
print(d)
Output:
{10: 'abc', 'xyz': 2.34, 1.23: None}
- Keys must be unique.
- When we store the data using duplicate key, existing data will be replaced.
accounts ={101:"harin", 102:"kiritin", 102:"ramya"}
print(accounts)
- Elements can be duplicated.
- for example, in Banking application, we process the accounts using account numbers.
- Account numbers are unique (keys)
- Account data can be duplicates (name, pin, balance….)
accounts ={101:"harin", 102:"kiritin", 103:"harin"}
print(accounts)