How to create a dictionary in Python

The inbuilt dict() function in Python is used to construct dictionaries.

Dictionaries are data types within Python that exist as key:value pairs.

Syntax

dict(**kwarg)
dict([mapping, **kwarg])
dict([iterable, **kwarg])

Examples

Dictionaries can be created with the following methods.

  1. Keyword arguments, passed as key:value pairs:
postcodes = dict(griffith=2603, belconnen=2617, phillip=2606)
print("Canberra postcodes: ", postcodes)
  1. Mapping, where another dictionary is passed as an argument:
postcodes_cbr = dict({'griffith':2603, 'belconnen':2617, 'phillip':2606})
print("Canberra postcodes: ", postcodes_cbr)
#Passing an optional keyword argument
postcodes_syd = dict({'sydney':2000, 'campbeltown':2560}, casula=2170)
print("Sydney postcodes: ", postcodes_syd)
  1. Iterables:
postcodes_cbr = dict([('griffith', 2603), ('belconnen', 2617)])
print("Canberra postcodes: ", postcodes_cbr)
#Passing an optional keyword argument
postcodes_syd = dict([('sydney',2000), ('campbeltown',2560)], casula=2170)
print("Sydney postcodes: ", postcodes_syd)