Dictionary is an unordered collection of key-value pairs. "dict" is a built-in Python class that represents a dictionary object.
The contents of a dict can be written as a series of key:value pairs within braces { } e.g. dict = {key1:value1, key2:value2, ... }.
The "empty dict" is just an empty pair of curly braces {}.
my_dict = {}
my_dict['a'] = 'alpha'
my_dict['g'] = 'gamma'
my_dict['o'] = 'omega'
print(my_dict)
{'a': 'alpha', 'g': 'gamma', 'o': 'omega'}
The keys will appear in an arbitrary order. The methods dict.keys() and dict.values() return lists of the keys or values.
my_dict.keys()
dict_keys(['a', 'g', 'o'])
print(my_dict['a'])
print(my_dict['g'])
print(my_dict['o'])
alpha gamma omega
my_dict['b'] = 'beta'
my_dict
{'a': 'alpha', 'g': 'gamma', 'o': 'omega', 'b': 'beta'}
del my_dict['a']
my_dict
{'g': 'gamma', 'o': 'omega', 'b': 'beta'}
value = my_dict.pop('o')
value
'omega'
del my_dict['invalidkey']
--------------------------------------------------------------------------- KeyError Traceback (most recent call last) <ipython-input-7-df2b2ffef6fa> in <module> ----> 1 del my_dict['invalidkey'] KeyError: 'invalidkey'
value = my_dict.pop('invalidkey')
my_dict