A dictionary is an unordered set of key-value pairs. A dictionary is indexed by keys, which can be strings, integers or tuples. A dictionary is like an associative array, if you are familiar with associative arrays from other programming languages.

A dictionary can be created in multiple ways, using {} or the dict() function. The following are some examples of ways to create dictionaries:

a=dict(one=1,two=2)
b={'one':1,'two':2}
c=dict(zip(['one','two'],[1,2]))
d=dict([('one',1),('two',2)])
e=dict({'one':1,'two':2})
print(a==b==c==d==e)
True


As you can see, all the variables hold the same dictionary. To create an empty dictionary, use {} or dict().

Note: I will be using the syntax used to initialize variable b, as it feels most natural to me. It’s a personal preference, use whichever syntax you are comfortable with.

There are multiple functions and methods that can be used to perform operations on dictionaries, some of whose usage is shown in the following examples.

Note: The operations are fairly straight forward to understand, so I won’t explain them in detail.

print('Dictionary contents ',a)
Dictionary contents  {'two': 2, 'one': 1}

print('len(a) ',len(a))
len(a)  2

print('a[\'one\'] ',a['one'])
a['one']  1

#changing value associated with 'one' key
a['one']=11
print('Dictionary contents after a[\'one\']=11 ',a)
Dictionary contents after a['one']=11  {'two': 2, 'one': 11}

a['one']=1
print('a[\'one\']=1 ','one' in a)
a['one']=1  True

#in operator cannot be used to check the existence of values
print('1 in a ',1 in a)
1 in a  False

#providing a default value if requested key does not exist
print('a.get(\'three\',3) ',a.get('three',3))
a.get('three',3)  3

print('a.keys() ',a.keys())
a.keys()  dict_keys(['two', 'one'])

print('a.values() ',a.values())
a.values()  dict_values([2, 1])

print('a.pop(\'one\') ',a.pop('one'))
a.pop('one')  1

print('Dictionary contents ',a)
Dictionary contents  {'two': 2}


The objects returned by dict.keys(), dict.values() and dict.items() are view objects. When the contents of the dictionary changes, the changes are reflected in the view objects. Example:

print('Dictionary contents ',a)
Dictionary contents  {'two': 2}

vals=a.values()
print(vals)
dict_values([2])

a['two']=22
print(vals)
dict_values([22])


References:

The code for today’s plog is here.