Dict

Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 6

Dictionary Data Structure:

--------------------------
We can use List,Tuple and Set to represent a group of individual objects as a
single entity. If we want to represent a group of objects as key-value pairs then
we should go for dict data type (Dictionary).

Ex:
rollno----name
phone number--address
ipaddress---domain name

i) Duplicate keys are not allowed but values can be duplicated.


ii) Hetrogeneous objects are allowed for both key and values.
iii) insertion order is not preserved, hence indexing and slicing concepts are not
applicable
iv) Dictionaries are mutable
v) Dictionaries are dynamic

How to create Dictionary?


-------------------------
d={} or d=dict() #we are creating empty dictionary.

We can add entries as follows:


d[100]="ram"
d[200]="shyam"
d[300]="shiva"
print(d)

syntax:
d={key:value, key:value}

If we know data in advance then we can create dictionary as follows:


d={100:'ram' ,200:'shyam', 300:'shiva'}

How to access data from the dictionary?


---------------------------------------
We can access data by using keys.
d={100:'ram' ,200:'shyam', 300:'shiva'}
print(d[100])
print(d[300])

If the specified key is not available then we will get KeyError


print(d[400]) # KeyError: 400

Note: We can prevent this by checking whether key is already available or not by
using in operator.
Ex:
if 400 in d:
print(d[400])

Q. Write a program to enter name and percentage marks in a dictionary and display
information on the screen.

How to update dictionaries?


d[key]=value
i) If the key is not available then a new entry will be added to the dictionary
with the specified key-value pair
ii) If the key is already available then old value will be replaced with new value
How to delete elements from dictionary?
del d[key]
It deletes entry associated with the specified key. If the key is not available
then we will get KeyError

d.clear(): To remove all entries from the dictionary

del d: To delete total dictionary.Now we cannot access d

Important functions of dictionary:


----------------------------------
1. dict(): To create a dictionary
d=dict() ===>It creates empty dictionary
d=dict({100:"apple",200:"boy"}) ==>It creates dictionary with specified elements
d=dict([(100,"ram"),(200,"shiva"),(300,"krishna")])==>It creates dictionary with
the given list of tuple elements

2. len(): Returns the number of items in the dictionary

3. clear(): To remove all elements from the dictionary

4.
d.get(key) If the key is available then returns the corresponding value otherwise
returns None. It wont raise any error.
d.get(key,defaultvalue) If the key is available then returns the corresponding
value otherwise returns default value.
Note: get()To get the value associated with the key

5. pop():
Syntax:
d.pop(key) It removes the entry associated with the specified key and returns the
corresponding value If the specified key is not available then we will get KeyError

6. popitem(): The popitem() method removes the item (key-value) that was last
inserted into the dictionary and returns it.
d={}
If the dictionary is empty then we will get KeyError
print(d.popitem()) ==>KeyError: 'popitem(): dictionary is empty'

Note: In versions before 3.7, the popitem() method removes a random(arbitrary)


item.

7. keys(): It returns list of all keys associated with dictionary.

8. values(): It returns list of all values associated with the dictionary.

9. items(): It returns list of tuples representing key-value pairs.


Ex:
[(k,v),(k,v),(k,v)]

10. copy(): To create exactly duplicate dictionary(cloned copy)


Ex:
d1=d.copy()

11. setdefault(): If the key is already available then this function returns the
corresponding value. If the key is not available then the specified key-value will
be added as new item to the dictionary.
Syntax:
d.setdefault(k,v)

12. update(): The update() method inserts the specified items to the dictionary.
The specified items can be a dictionary, or an iterable object with key value
pairs.
Syntax
dictionary.update(iterable)
Ex:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
car.update({"color": "White"})
print(car)
Ex:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
car.update({"color": "White",'price':10000000})
print(car)

13. fromkeys() Method: The fromkeys() method returns a dictionary with the
specified keys and the specified value.
Syntax
dict.fromkeys(keys, value)
Ex:
x = ('key1', 'key2', 'key3')
thisdict = dict.fromkeys(x)
print(thisdict)
Parameter
keys: Required. An iterable specifying the keys of the new dictionary
value: Optional. The value for all keys. Default value is None

14. max():

15. min():

16. count():

17: sorted():

Q. Write a program to take dictionary from the keyboard and print the sum of
values?
d=eval(input("Enter dictionary:"))
s=sum(d.values())
print("Sum= ",s)

Q. Write a program to find number of occurrences of each letter present in the


given string?
word=input("Enter any word: ")
d={}
for x in word:
d[x]=d.get(x,0)+1
for k,v in d.items():
print(k,"occurred ",v," times")
Q. Write a program to find number of occurrences of each vowel present in the given
string?
word=input("Enter any word: ")
vowels={'a','e','i','o','u'}
d={}
for x in word:
if x in vowels:
d[x]=d.get(x,0)+1
for k,v in sorted(d.items()):
print(k,"occurred ",v," times")

Q. Write a program to accept student name and marks from the keyboard and creates a
dictionary. Also display student marks by taking student name as input?

Dictionary Comprehension: Comprehension concept applicable for dictionaries also.


Ex:
squares={x:x*x for x in range(1,6)}
print(squares)
Ex:
doubles={x:2*x for x in range(1,6)}
print(doubles)

-----------------------------------------------------------------------------------
-----------------------------------------
Practice Codes:
-----------------------------------------------------------------------------------
-----------------------------------------

1. Write a Python script to sort (ascending and descending) a dictionary by value.

2. Write a Python script to concatenate the following dictionaries to create a new


one. Go to the editor
Sample Dictionary :
dic1={1:10, 2:20}
dic2={3:30, 4:40}
dic3={5:50,6:60}
Expected Result : {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}
Sol:
dic1={1:10, 2:20}
dic2={3:30, 4:40}
dic3={5:50,6:60}
dic4 = {}
for d in (dic1, dic2, dic3):
print(d)
dic4.update(d)
print(dic4)

3. Write a Python script to check whether a given key already exists in a


dictionary.

4. Write a Python script to add a key to a dictionary.

5. Write a Python program to iterate over dictionaries using for loops.

6. Write a Python script to generate and print a dictionary that contains a number
(between 1 and n) in the form (x, x*x).
Sample Dictionary ( n = 5)
Expected Output : {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Sol:
n=int(input("Input a number "))
d = dict()
for x in range(1,n+1):
d[x]=x*x
print(d)

7. Write a Python script to print a dictionary where the keys are numbers between 1
and 15 (both included) and the values are the square of the keys.
Sample Dictionary
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100, 11: 121, 12:
144, 13: 169, 14: 196, 15: 225}
Sol:
d=dict()
for x in range(1,16):
d[x]=x**2
print(d)

8. Write a Python script to merge two Python dictionaries.


Sol:
d1 = {'a': 100, 'b': 200}
d2 = {'x': 300, 'y': 200}
d = d1.copy()
d.update(d2)

9. Write a Python program to iterate over dictionaries using for loops.


Sol:
d = {'Red': 1, 'Green': 2, 'Blue': 3}
for color_key, value in d.items():
print(color_key, 'corresponds to ', d[color_key])

10. Write a Python program to sum all the items in a dictionary.


Sol:
my_dict = {'data1':100,'data2':-54,'data3':247}
print(sum(my_dict.values()))
print(d)

11. Write a Python program to multiply all the items in a dictionary.


Sol:
my_dict = {'data1':100,'data2':-54,'data3':247}
result=1
for key in my_dict:
result=result * my_dict[key]
print(result)

12. Write a Python program to remove a key from a dictionary.

13. Write a Python program to map two lists into a dictionary.

14. Write a Python program to sort a given dictionary by key.


Sol:
color_dict = {'red':'#FF0000',
'green':'#008000',
'black':'#000000',
'white':'#FFFFFF'}
for key in sorted(color_dict):
print('{} : {}'.format(key,color_dict[key]))
15. Write a Python program to get the maximum and minimum values of a dictionary.
Sol:
my_dict = {'x':500, 'y':5874, 'z': 560}
max = max(my_dict.values())
min = min(my_dict.values())
print(max,min)

16. Write a Python program to check if a dictionary is empty or not.


Sol:
my_dict = {}
if not bool(my_dict):
print("Dictionary is empty")

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy