[go: up one dir, main page]

0% found this document useful (0 votes)
14 views57 pages

DICTIONARY

The document provides a comprehensive overview of dictionaries in Python, detailing their properties, creation methods, and various functions. It explains that dictionaries are mutable, unordered collections of key-value pairs, where keys must be of immutable types. Additionally, it covers operations such as accessing, updating, deleting, and nested dictionaries, along with examples of each functionality.

Uploaded by

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

DICTIONARY

The document provides a comprehensive overview of dictionaries in Python, detailing their properties, creation methods, and various functions. It explains that dictionaries are mutable, unordered collections of key-value pairs, where keys must be of immutable types. Additionally, it covers operations such as accessing, updating, deleting, and nested dictionaries, along with examples of each functionality.

Uploaded by

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

DICTIONARY

1 . Dictionary is a mutable data type.

2. Dictionary is not ordered data type

3. It is enclosed in {}

4. It contains key value pairs separated by “ : ”

5. Keys of the dictionary are unique.

6. If the new value is assigned to the existing key then value will be changed for the existing
key.

7. If new value is assigned to new key then the dictionary will be updated with new key value
pair.
DICTIONARY
The keys of the dictionary are of immutable data
type.

So key can be a string, a number , tuple, a


character.

List cannot be the key of the dictionary because


the list is a mutable data type.
DICTIONARY
d={[10,20]:1}
print(d)

Output:-
d={[10,20]:1}
TypeError: unhashable type: 'list'
DICTIONARY
PROGRAM:-
d={1:"sunday",3:"tuesday",2:"monday",5:"thrus
day"}
print(d)
print(d[5])
d[5]="friday"
print(d)
DICTIONARY
OUTPUT

{1: 'sunday', 3: 'tuesday', 2: 'monday', 5:


'thrusday'}
thrusday
{1: 'sunday', 3: 'tuesday', 2: 'monday', 5: 'friday'}
DICTIONARY
Dictionary can be created in many ways:-

1.Empty dictionary can be created in the following manner


d={}
print(d)
2. Empty dictionary can also be created by using dict() function
d=dict()
print (d)
OUTPUT:-

{}
{}
DICTIONARY
3. Dictionary can be created in the following manner by passing key value as a parameter.
d1=dict(1:”a”)
Print(d1)

4. Dictionary can be created by passing existing dictionary to the dict() function.


d2=dict(d1)
print(d2)

Changes made to d1 or d2 will not be reflected in both as they refer to different locations.
OUTPUT:-
{'name': 1, 'age': 35, 'salary': 35000}
{'name': 1, 'age': 35, 'salary': 35000}
DICTIONARY
5. Dictionary can be created by assigning existing dictionary to the new
variable
d3=d2
print(d3)
If any changes made to any one dictionary in the above example, the changes
will be reflected in both as they both refer to same location.
6. d=dict()
print(d)
d[1]="amit"
d["age"]=35
d["salary"]=35000
print(d)
DICTIONARY

OUTPUT:-

{'name': 1, 'age': 35, 'salary': 35000}

{1: 'amit', 'age': 35, 'salary': 35000}


DICTIONARY
7. Dictionary can be created by passing key values as a parameter to the
dict() function where key value pair is separated by “=“

Here if the key is the string, then it is not required to keep the string in the
double quote as shown in the following example.
d=dict(name="raman",age=25,salary=35000)
print(d)
OUTPUT
{“name”:”raman”,”age”:25,”salary”:35000}
DICTIONARY

8. Dictionary can be created by passing the dictionary as a parameter.

d=dict({"name":"raman","age":25,"salary":33000})
print(d)

OUTPUT:
{"name":"raman","age":25,"salary":33000}
DICTIONARY

9. Dictionary can be created by passing nested list which contain both key
and values separated by “,”

d1=dict([["name","aman"],["age",25],["salary",45000]])
print(d1)

OUTPUT:-
{“name”:”aman”,”age”:25,”salary”:45000}
DICTIONARY

10. Dictionary can be created by passing nested tuple which contains key
value pairs separated by “,” as a parameter.

d2=dict((("name","aman"),("age",25),("salary",45000)))
print(d2)

OUTPUT:-
{“name”:”aman”,”age”:25,”salary”:45000}
DICTIONARY

11.Dictionary can be created by passing tuple which contains list as a


parameter to the function dict

d3=dict((["name","aman"],["age",25],["salary",45000]))
print(d3)

OUTFPUT:-
“name”:”aman”,”age”:25,”salary”:45000}
DICTIONARY

12. Dictionary can be created by passing list which contains tuple as a


parameter to the function dict ()
d4=dict([("name","aman"),("age",25),("salary",45000)])
print(d4)

OUTFPUT:-
“name”:”aman”,”age”:25,”salary”:45000}
DICTIONARY
13. Dictionary can be created by passing set of keys and values separately
separated by “,” to zip function and passing it as parameter to dict()
employee=dict(zip(("ename","salary","age"),("sunil",35000,34)))
print(employee)
employee=dict(zip(["ename","salary","age"],["sunil",35000,34]))
print(employee)
OUTPUT
{“ename”:”sunil”,”salary”:35000,”age”:34}
14. Dictionary can be created by accepting both
keys and values at run time as shown below:
d={}
n=int(input("accept limit?"))
for i in range(n):
k=int(input("enter the key"))
v=input("enter value")
d[k]=v
print(d)
OUTPUT
accept limit?3
enter the key1
enter valueSUNDAY
enter the key2
enter valueMONDAY
enter the key2
enter valueTUESDAY
{1: 'SUNDAY', 2: 'TUESDAY'}
DICTIONARY

14. In order to access the respective value of the key, the following
statement should be written.

D={1:”Sunday”, 2:”Monday”,3:”Tuesday”}

print(D[3])
OUTPUT:-
Tuesday
DICTIONARY

15. D={1:”Sunday”, 2:”Monday”,3:”Tuesday”}

In order to change value of the particular key the following statement


should be written.
D[3]=“Saturday”
Print(D)
{1:”Sunday”, 2:”Monday”,3:”Saturday”}
DICTIONARY

16. The key of the dictionary can never be a mutable data type. So list can
never be used as a key of the dictionary as it is a mutable data type.
The key of the dictionary can be a string, number, tuple etc.

D={[1,2,3]:”Aman”,2:”kamala”}

The above statement will throw an error.


DICTIONARY-FUNCTIONS

1. The function keys() can be used to extract keys of the dictionary

2. The function values() can be used to extract values of the dictionary.

3. The function items() can be used to extract both key and values of the
dictionary..
DICTIONARY
day={1:"sunday",2:"monday",3:"tuesday"}
print(day.keys())
print(day.values())
print(day.items())

OUTPUT
dict_keys([1, 2, 3])
dict_values(['sunday', 'monday', 'tuesday'])
dict_items([(1, 'sunday'), (2, 'monday'), (3, 'tuesday')])
DICTIONARY
4.sorted()-sorts all the keys of the dictionary also returns the sorted keys in
the form of list
b={5:"lead",3:"win",7:"success"}
b=sorted(b)
print(b)
b={5:"lead",3:"win",7:"success"}
b=sorted(b.keys())
print(b)
b={5:"lead",3:"win",7:"success"}#sorting done on the values only
b=sorted(b.values())
print(b)
DICTIONARY

OUTPUT

[3, 5, 7]
[3, 5, 7]
['lead', 'success', 'win']
DICTIONARY
b={5:"lead",3:"win",7:"success"}
b=sorted(b.items())
print(b)

OUTPUT:
[(3, 'win'), (5, 'lead'), (7, 'success')]
DICTIONARY

5. len()-len() function calculates the length of the dictionary.

book={1:"abc",3:"xyz",2:"uvw"}
C=len(book)
Print©

Output:
3
DICTIONARY
6.setdefault(key,value)-This function takes key value as parameter
separated by coma and set the key values to the dictionary and this
function will return the value of the key. This works as an update
function but this function will not update the value for the existing
key. Update takes only 1 parameter. Set default takes two parameters.
b={5:"lead",3:"win",7:"success"}
print(b)
c=b.setdefault(3,"win")
print(c)
print(b)
c=b.setdefault(3,"bigwin")
print(c)
print(b)
SET DEFAULT() UPDATE()

TAKES TWO PARAMETERS UPDATE TAKES ONLY ONE


PARAMETER
Takes (KEY VALUE SEPARATED BY Takes key value pairs separated by
COMA) as parameter “:”

It returns the value of key that was It returns none


set

It will not update existing key. It will update existing key.


DICTIONARY

OUTPUT

{5: 'lead', 3: 'win', 7: 'success'}


win
{5: 'lead', 3: 'win', 7: 'success'}
win
{5: 'lead', 3: 'win', 7: 'success'}
DICTIONARY

7. update{dictionary}-This function takes key value pair in the form of a


dictionary and adds them to the existing dictionary

book={1:"abc",3:"xyz",2:"uvw"}
book.update({"qty1":15})
print(book)
DICTIONARY

8.get(key)-This function fetches the value of the key passed as a


parameter.

book={1:"abc",3:"xyz",2:"uvw“,”qty”:155}
print(book.get("qty1"))

OUTPUT:
155
DICTIONARY
9.del dictionary-del function deletes the dictionary.
Eg:-del book

10.del(dictionary[key])-removes the value of the key passed as a


parameter.
book={1:"abc",3:"xyz",2:"uvw"}
del book[2]

Output:-
{1:"abc",3:"xyz"}
DICTIONARY

11. Copy()-This function copies all the key values of the existing
dictionary to the new dictionary.

book={1:"abc",3:"xyz",2:"uvw"}
b=book.copy()
print(book)
print(b)
DICTIONARY

OUTPUT:

{1: 'abc', 3: 'xyz', 2: 'uvw'}


{1: 'abc', 3: 'xyz', 2: 'uvw'}
DICTIONARY
12. max()-This function finds the maximum value out of the keys provided
in the dictionary.

13. min()-This function find the minimum value out of the keys provided
in the dictionary.

14. sum()-This function finds the sum of the all keys present in the
dictionary.
The above functions works in the dictionary provided all the keys are of
integers.
DICTIONARY
book={1:"abc",3:"xyz",2:"uvw"}. The following functions work in the
case of strings also except sum() function. In order to make max(),
min() function to work on the keys of the dictionary, all keys of the
dictionary should of same data type.
print(max(book))
print(min(book))
print(sum(book))
OUTPUT:-
3
1
6
DICTIONARY

15. popitem()-This function pops the last key value pair from the
dictionary. The popped item is retrieved in the form of a tuple.

book={1:"abc",3:"xyz",2:"uvw"}
print(book.popitem())

Output:-
(2, 'uvw')
DICTIONARY
16.pop(key)-This function will remove the key value of key passed as a
parameter from the dictionary. This function returns the value.
book={1:"abc",3:"xyz",2:"uvw"}
print(book)
print(book.pop(3))
print(book)
OUTPUT:-
{1: 'abc', 3: 'xyz', 2: 'uvw'}
xyz
{1: 'abc', 2: 'uvw'}
DICTIONARY
17.clear()-This function clears all the key value pairs present in the
dictionary.
book={1:"abc",3:"xyz",2:"uvw"}
print(book)
book.clear()
print(book)
Output
{1: 'abc', 3: 'xyz', 2: 'uvw'}
{}
DICTIONARY
Nested dictionary:-Dictionary with in the dictionary is known as nested
dictionary.
If the programmer has to save many particulars of many students then
nested dictionary to be used.
stu={1:{"name":"sumit","m1":99,"m2":98},2:
{"name":"rakesh","m1":98,"m2":98}}
print(stu)
In the above example, 1 and 2 are outer keys
And name :sumit, m1:99, m2:98 are inner key value pairs of the outer key
Roll 1.
DICTIONARY

OUTPUT:-

{1: {'name': 'sumit', 'm1': 99, 'm2': 98}, 2: {'name': 'rakesh', 'm1': 98, 'm2':
98}}
DICTIONARY
All the values of the outer key can be accessed in the following manner.
stu={1:{"name":"sumit","m1":99,"m2":98},2:
{"name":"rakesh","m1":98,"m2":98}}
print(stu[1])
If the programmer wants to get the particular value of the key for the given
outer key, then the statement should be written as follows:
stu={1:{"name":"sumit","m1":99,"m2":98},2:
{"name":"rakesh","m1":98,"m2":98}}
print(stu[1]["m1"])
DICTIONARY

OUTPUT:-

{'name': 'sumit', 'm1': 99, 'm2': 98}

99
DICTIONARY
stu={1:{"name":"sumit","m1":99,"m2":98},2:
{"name":"rakesh","m1":98,"m2":98}}

print(stu[2])
print(stu[2]["name"])
DICTIONARY

OUTPUT:-

{'name': 'rakesh', 'm1': 98, 'm2': 98}

rakesh
DICTIONARY

HOW TO ACCEPT VALUES AT RUN TIME IN THE NESTED


DICGTIONARY??
item={}
tot=0
n=int(input("accept how many items?:"))
for i in range(n):
id=input("accept key for item id")
item[id]={}
item[id]['inm']= input("accept name ")
DICTIONARY
item[id]["iquantity"]=int(input("Accept quantity"))
item[id]["iprice"]=float(input("Accept price"))

item[id]["tprice"]=item[id]["iquantity"]*item[id]["iprice"]
print(item)
DICTIONARY
INPUT & OUTPUT
accept name nuts
Accept quantity20
Accept price30
accept key for item id1002
accept name bolts
Accept quantity30
Accept price20
accept key for item id1003
accept name wheel
Accept quantity5
Accept price200
DICTIONARY

{'1001': {'inm': 'nuts', 'iquantity': 20, 'iprice': 30.0, 'tprice': 600.0}, '1002':
{'inm': 'bolts', 'iquantity': 30, 'iprice': 20.0, 'tprice': 600.0}, '1003':
{'inm': 'wheel', 'iquantity': 5, 'iprice': 200.0, 'tprice': 1000.0}}
DICTIONARY
DICTIONARY
DICTIONARY
DICTIONARY
DICTIONARY
DICTIONARY
DICTIONARY

You might also like