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 typestr
. - 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 nesteddict
. - 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.
In [1]:
# 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}
In [2]:
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'>
In [3]:
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'>
In [4]:
d.update([('phone_numbers', [1234567890, 2345679180])])
In [5]:
d
Out[5]:
{'id': 1, 'first_name': 'Scott', 'last_name': 'Tiger', 'amount': 1000.0, 'phone_numbers': [1234567890, 2345679180]}
In [6]:
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'>
In [7]:
d['address'] = {'street': '1234 ABC Towers', 'city': 'Round Rock', 'state': 'Texas', 'zip': 78664}
In [8]:
d
Out[8]:
{'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}}
In [9]:
d['address']
Out[9]:
{'street': '1234 ABC Towers', 'city': 'Round Rock', 'state': 'Texas', 'zip': 78664}
In [10]:
type(d['address'])
Out[10]:
dict
In [11]:
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'>