# Lesson 5 - Dictionary

• Dictionaries help in assigning a key for every value in the sequence.

citydict =

{
“city” : “Chicago”,
“population”, “2.8 million”,
“density” : 12000
}

print(citydict)

A dictionary is a collection which is ordered, changeable and do not allow duplicates.
Dictionaries are written with curly brackets, and have keys and values:

Duplicate keys are not allowed in dict, for example

citydict =

{
“city” : “Chicago”,
“population”, “2.8 million”,
“density” : 12000
“density” ” 11000 // not allowed
}

Dictionary length

A dictionary length mean the number of items in it.
len(citydict) returns 3

Accessing a dictionary item using []

A dictionary item can be accessed using its key.

Example

x = citydict[“Population”]
print(x)  outputs “2.8 million”

Accessing a dictionary item using get function

Another way of accessing a dictionary item using get() function

Example

x = citydict.get(“Population”)
print(x)  outputs “2.8 million”

Getting all keys of dict

keys()  method returns all the keys of a dictionary

Example
x = report.keys()
print(x)  outputs

Getting all values of dict

values()  method returns all the values of a dictionary

Example
report = { “subject”: “Maths”, “grade”:”A”, “marks” : 99}
x = report.values()
print(x)  outputs
dict_keys([‘Maths’, ‘A’, ’99’])

Getting all items of dict

items()  method returns all the values of a dictionary

Example
report = { “subject”: “Maths”, “grade”:”A”, “marks” : 99}
x = report.items()
print(x)  outputs dict_items([(‘subject’, ‘Maths’), (‘grade’, ‘A’), (‘marks’, 99)])

Add a new item in the Dictionary

One can easily add a new item to an existing dictionary using the following syntax
For example you have a dictionary called report
report= { “subject”: “Maths”, “grade”:”A”, “marks” : 99}

And you want to add a new item called rank with a value of 7
report[“rank”] = 7

Check if the item is added or not
print(report) outputs {‘subject’: ‘Maths’, ‘grade’: ‘A’, ‘marks’: 99, ‘rank’: 7}

Change existing item in the Dictionary

To change an item , for example  marks from 99 to 97
report[“marks”] = 97

or
report.update({“marks”: 97})

Remove an item from the Dictionary

There are several methods to remove an item. One such method is pop()
For example to remove rank  from the report

report.pop(“rank”)
or
del report[“rank”]

Emptying a dictionary

The clear() method empties the dictionary.
report.clear()

Nested dictionaries

A dictionary can contain another dictionary, this is called nested dictionaries.

For example student dictionary is inserted inside report