Python Foundations - Assessments

44 / 54

Dictionaries

A dictionary is nothing much different from the list.

In the list, the indices are integers but in a dictionary, the indices can be of any type. It's like a key mapping to a value.

d = dict()
print(d)

It prints {} ie.empty dictionary. dict is the function that creates a dictionary.

For adding and accessing the elements we make use of square brackets. Let us make a dictionary containing the number of coins each of 1 rupee, 2 rupees, 5 rupees, and 10 rupees.

d['1 rupee coins'] = 10
d['2 rupees coins'] = 5
d['5 rupees coins'] = 6
d['10 rupees coins'] = 12

Here the keys are strings and values are integers. But, they can be of any type of your choice. If we print the dictionary again, we can see the key-value pairs printed as follows.

print(d)

{'1 rupee coins': 10, '2 rupees coins': 5, '5 rupees coins': 6, '10 rupees coins': 12}

Now what will be the output of print(d['5 rupees coins']+d['10 rupees coins'])

We can also directly create a dictionary by assigning the values in one go,

d = { 'one' : 1 , 'two' : 2, 'three' : 3, 'four': 4 }

Now if you print d, it may or may not come in the order one, two and three. In general, the order of items in a dictionary is unpredictable. But that doesn't concern us in any way because the elements of a dictionary are never indexed with integer indices. Instead, we use the keys to get some value.

Some functions work somewhat like they work for lists, can you tell the outputs of these,

d = { 'one' : 1 , 'two' : 2, 'three' : 3, 'four': 4 }
print(len(d))

print('three' in d)

print(4 in d)

print(5 in d and 2 in d)

See Answer

No hints are availble for this assesment


Note - Having trouble with the assessment engine? Follow the steps listed here

Loading comments...