Common Examples - dict

Let us see some common examples while creating dict in Python. If you are familiar with JSON, dict is similar to JSON.

  • A dict can have key value pairs where key is of any type and value is of any type.

  • However, typically we use attribute names as keys for dict. They are typically of type str.

  • The value can be of simple types such as int, float, str etc or it can be object of some custom type.

  • The value can also be of type list or nested dict.

  • An individual might have multiple phone numbers and hence we can define it as list.

  • An individual address might have street, city, state and zip and hence we can define it as nested dict.

  • Let us see some examples.

# All attribute names are of type str and values are of type int, str or float
d = {'id': 1, 'first_name': 'Scott', 'last_name': 'Tiger', 'amount': 1000.0}
for key in d.keys():
    print(f'type of attribute name {key} is {type(key)}')
type of attribute name id is <class 'str'>
type of attribute name first_name is <class 'str'>
type of attribute name last_name is <class 'str'>
type of attribute name amount is <class 'str'>
for value in d.values():
    print(f'type of value {value} is {type(value)}')
type of value 1 is <class 'int'>
type of value Scott is <class 'str'>
type of value Tiger is <class 'str'>
type of value 1000.0 is <class 'float'>
d.update([('phone_numbers', [1234567890, 2345679180])])
d
{'id': 1,
 'first_name': 'Scott',
 'last_name': 'Tiger',
 'amount': 1000.0,
 'phone_numbers': [1234567890, 2345679180]}
for value in d.values():
    print(f'type of value {value} is {type(value)}')
type of value 1 is <class 'int'>
type of value Scott is <class 'str'>
type of value Tiger is <class 'str'>
type of value 1000.0 is <class 'float'>
type of value [1234567890, 2345679180] is <class 'list'>
d['address'] = {'street': '1234 ABC Towers', 'city': 'Round Rock', 'state': 'Texas', 'zip': 78664}
d
{'id': 1,
 'first_name': 'Scott',
 'last_name': 'Tiger',
 'amount': 1000.0,
 'phone_numbers': [1234567890, 2345679180],
 'address': {'street': '1234 ABC Towers',
  'city': 'Round Rock',
  'state': 'Texas',
  'zip': 78664}}
d['address']
{'street': '1234 ABC Towers',
 'city': 'Round Rock',
 'state': 'Texas',
 'zip': 78664}
type(d['address'])
dict
for value in d.values():
    print(f'type of value {value} is {type(value)}')
type of value 1 is <class 'int'>
type of value Scott is <class 'str'>
type of value Tiger is <class 'str'>
type of value 1000.0 is <class 'float'>
type of value [1234567890, 2345679180] is <class 'list'>
type of value {'street': '1234 ABC Towers', 'city': 'Round Rock', 'state': 'Texas', 'zip': 78664} is <class 'dict'>