Great! Let's analyze how to create a dictionary in detail.
phonebook = {'Mary': '8349374', 'Anne': '7439834', 'John': '3472983'}
Here, we introduced a dictionary variable with a pair of curly braces { }
. Inside, we can provide multiple key-value pairs. Keys are separated from values with a colon (:
), and key-value pairs are separated with commas. For instance, in 'Mary':'8349374'
, 'Mary'
is a string key, and '8349374'
is a string value.
Keys and values can be of the same type, or their types can differ. For instance:
points = {'John': 83} # string key, integer value
favorite_colors = {'Adam': 'red', 'John': 'blue', 'Jack': 'black'} # string key, string value
annual_weights = {2010: 85.5, 2011: 88.9, 2012: 87.0} # integer key, float value