0% found this document useful (0 votes)
7 views14 pages

Dictionary

Uploaded by

sherlockalt3
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views14 pages

Dictionary

Uploaded by

sherlockalt3
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

Dictionary: Dictionaries are used to store data values in key:value pairs.

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:

How to create dictionary?

"""

dict = {

"brand": "suzuki",

"model": "Swift",

"year": 2020

print(dict)

"""Dictionary *Items* - Dictionary items are presented in key:value pairs, and can be referred to by
using the key name

Print the brand value of dictionary

"""

dict = {

"brand": "suzuki",

"model": "Swift",

"year": 2020

print(dict["brand"])

print(dict["year"])

"""Ordered or Unordered?

Dictionaries are ordered, it means that the items have a defined order, and that order will
not change.
Unordered means that the items do not have a defined order, you cannot refer to an item by using
an index.

Changeable - Dictionaries are changeable, meaning that we can change, add or remove items after
the dictionary has been created.

Duplicates Not Allowed

Dictionaries cannot have two items with the same key

"""

dict = {

"brand": "suzuki",

"model": "Swift",

"year": 2020,

"year": 2022

print(dict)

"""Dictionary Length

To determine how many items a dictionary has, use the len() function

"""

dict = {

"brand": "suzuki",

"model": "Swift",

"year": 2020,

"year": 2022,

"color": "red"

print(len(dict))
"""Dictionary Items - Data Types

The values in dictionary items can be of any data type

"""

dict = {

"brand": "suzuki",

"model": "Swift",

"year": 2020,

"electric": False,

"colors": ["red","grey","white","blue"],

"colors1": "red"

print(dict)

"""type()

From Python's perspective, dictionaries are defined as objects with the data type 'dict' <class
'dict'>

"""

dict = {

"brand": "suzuki",

"model": "Swift",

"year": 2020,

"electric": False,

"colors": ["red","grey","white","blue"]

print(type(dict))

"""dict() Constructor - It is also possible to use the dict() constructor to make a dictionary."""
"""Accessing Items - You can access the items of a dictionary by referring to its key name, inside
square brackets"""

dict = {

"brand": "suzuki",

"model": "Swift",

"year": 2020,

"electric": False,

"colors": ["red","grey","white","blue"]

x=dict["model"]

print(x)

x=dict["electric"]

y=dict["colors"]

print(y)

print(x)

"""There is also a method called get() that will give you the same result"""

from typing import Any

x = dict.get("model")

print(x)

x=dict.get(Any)

print(x)

"""Get Keys

The keys() method will return a list of all the keys in the dictionary

"""

x = dict.keys()
print(x)

x=dict.values()

print(x)

car = {

"brand": "maruti",

"model": "Swift Dzire",

"year": 1964

x = car.keys()

print(x)

car["color"] = "white"

print(x)

car = {

"brand": "maruti",

"model": "Swift Dzire",

"year": 2020

x = car.values()

print(x)

car["color"] = "white"

print(x)

"""Get Items

The items() method will return each item in a dictionary, as tuples in a list

"""

x = dict.items()

print(x)
"""Make a change in the original dictionary, and see that the items list gets updated as well"""

car = {

"brand": "maruti",

"model": "Swift Dzire",

"year": 2020

x = car.items()

print(x)

car["color"] = "white"

print(x)

"""Check if Key Exists

To determine if a specified key is present in a dictionary use the in keyword:

"""

car = {

"brand": "maruti",

"model": "Swift Dzire",

"year": 2020

if "model" in car:

print("Yes")

"""Change Values -

You can change the value of a specific item by referring to its key name

Change the "year" to 2024

"""

car = {

"brand": "maruti",
"model": "Swift Dzire",

"year": 2020

car["year"]=2024

print(car)

"""Update Dictionary -

The update() method will update the dictionary with the items from the given argument.

The argument must be a dictionary, or an iterable object with key:value pairs.

"""

car = {

"brand": "maruti",

"model": "Swift Dzire",

"year": 2020

car.update({"year": 2024})

print(car)

"""Adding Items -

Adding an item to the dictionary is done by using a new index key and assigning a value to it

"""

from contextlib import redirect_stderr

car = {

"brand": "maruti",

"model": "Swift Dzire",

"year": 2020

car["color"] = "red"
car["engine fuel"] ="petrol/diesel"

print(car)

"""Removing Items -

There are several methods to remove items from a dictionary

"""

car = {

"brand": "maruti",

"model": "Swift Dzire",

"year": 2020

car.pop("model")

print(car)

"""The popitem() method removes the last inserted item"""

car = {

"brand": "maruti",

"model": "Swift Dzire",

"year": 2020

car.popitem()

print(car)

"""The del keyword removes the item with the specified key name"""

car = {

"brand": "maruti",

"model": "Swift Dzire",

"year": 2020
}

del car["model"]

print(car)

"""Loop Through a Dictionary - When looping through a dictionary, the return value are the keys of
the dictionary, but there are methods to return the values as well."""

for x in dict:

print(x)

dict = {

"brand": "suzuki",

"model": "Swift",

"year": 2020,

"electric": False,

"colors": ["red","grey","white","blue"]

for x in dict:

print(x)

"""Print all values in the dictionary"""

for x in dict:

print(dict[x])

"""You can also use the values() method to return values of a dictionary"""

for x in dict.values():

print(x)

"""You can use the keys() method to return the keys of a dictionary"""
for x in dict.keys():

print(x)

"""Loop through both keys and values, by using the items() method"""

for x, y in dict.items():

print(x, y)

"""Copy Dictionaries - You cannot copy a dictionary simply by typing dict2 = dict1, because: dict2 will
only be a reference to dict1, and changes made in dict1 will automatically also be made in dict2.

There are ways to make a copy, one way is to use the built-in Dictionary method copy().

"""

dict = {

"brand": "suzuki",

"model": "Swift",

"year": 2020,

"electric": False,

"colors": ["red","grey","white","blue"]

dict11 = dict.copy()

print(dict11)

"""Nested Dictionaries - A dictionary can contain dictionaries Create a


dictionary that contain three dictionaries"""

myfamily = {

"child1" : {

"name" : "raja",

"year" : 2004
},

"child2" : {

"name" : "rani",

"year" : 2007

},

"child3" : {

"name" : "raj",

"year" : 2011

"""Create three dictionaries, then create one dictionary that will contain the other three
dictionaries"""

child1 = {

"name" : "raja",

"year" : 2004

child2 = {

"name" : "rani",

"year" : 2007

child3 = {

"name" : "raj",

"year" : 2011

myfamily = {

"child1" : child1,

"child2" : child2,

"child3" : child3

}
"""Access Items in Nested Dictionaries -

To access items from a nested dictionary, you use the name of the dictionaries, starting with the
outer dictionary

"""

print(myfamily["child2"]["name"])

print(myfamily["child3"]["year"])

"""Loop Through Nested Dictionaries -

You can loop through a dictionary by using the items() method

"""

for x, obj in myfamily.items():

print(x)

for y in obj:

print(y + ':', obj[y])

"""Python program to get the nested dictionaries from a dictionary"""

myfamily = {

"child1" : {

"name" : "raja",

"year" : 2004

},

"child2" : {

"name" : "rani",

"year" : 2007

},

"child3" : {
"name" : "raj",

"year" : 2011

for i in myfamily:

# display

print(myfamily[i])

"""Python program to get keys from the nested dictionary"""

myfamily = {

"child1" : {

"name" : "raja",

"year" : 2004

},

"child2" : {

"name" : "rani",

"year" : 2007

},

"child3" : {

"name" : "raj",

"year" : 2011

for i in myfamily:

print(myfamily[i].keys())

myfamily = {

"child1" : {

"name" : "raja",
"year" : 2004

},

"child2" : {

"name" : "rani",

"year" : 2007

},

"child3" : {

"name" : "raj",

"year" : 2011

for i in myfamily:

print(myfamily[i].values())

You might also like