Python Dictionary Methods and Dictionary Comprehension

Adding Key Value Pairs to a Dictionary

 
      di={}
      di["Satish"]="Python"
      di["Ram"]="Physics"
      di["Tom"]="Chemistry"
      print(di) 

    
Output

Printing Dictionaries

 
      di={'Satish': 'C++', 'Ram': 'Physics', 'Tom': 'Chemistry'}
print(di)
print(di["Satish"])
print(di.keys())
print(di.values())

    
Output {'Satish': 'C++', 'Ram': 'Physics', 'Tom': 'Chemistry'} C++ dict_keys(['Satish', 'Ram', 'Tom']) dict_values(['C++', 'Physics', 'Chemistry'])

Removing Elements from a Dictionary

 
      di={(1,2): 'C++', 'Ram': 'Physics'}
      del di[(1,2)]
      print(di) 

    
Output {'Ram': 'Physics'}

Clearing Elements from a Dictionary

 
      di={(1,2): 'C++', 'Ram': 'Physics'}
di.clear()
print(di)

    
Output {}

Printing the elements in a Dictionary using a For Loop

 
      di={"Satish": "C++", "Ram": "Physics", "Tom": "Chemistry"}
for item in di:
    print(item +":"+di[item])

    
Output Satish:C++ Ram:Physics Tom:Chemistry

Printing Keys from a Dictionary

 
      di={"Satish": "C++", "Ram": "Physics", "Tom": "Chemistry"}
for item in di:
    print(item)

    
Output Satish Ram Tom

Printing Values from a Dictionary

 
      di={"Satish": "C++", "Ram": "Physics", "Tom": "Chemistry"}
for item in di:
    print(di[item])

    
Output C++ Physics Chemistry

Dictionary Shallow Copy

 
      import copy
di1={"Satish":[123,234,435],"Ramesh":"C++"}
di2={}
di2=di1.copy()
di2["Satish"][0]=125
print(di1)
print(di2)

    
Output {'Satish': [125, 234, 435], 'Ramesh': 'C++'} {'Satish': [125, 234, 435], 'Ramesh': 'C++'}

Creating another Dictionary using .fromkeys method

 
      keys={"ramesh","satish","tom"}
di={}
values="none"
d2=di.fromkeys(keys,values)
print(d2)

    
Output {'ramesh': 'none', 'satish': 'none', 'tom': 'none'}

Creating another Dictionary from Values using .fromKeys

 
      keys={"satish","ramesh","sam"}
      values={1}
      d=dict.fromkeys(keys,values)
      print(d)      

    
Output {'satish': {1}, 'sam': {1}, 'ramesh': {1}}

Getting the value for a specific key using .get method

 
      di={"satish":"python","ramesh":"physics"}
print(di.get("satish"))
print(di.get("sat"))

    
Output python None

Getting the items using the .items method

 
      di={"satish":"python","ramesh":"physics"}
for (key,value) in di.items():
print(key,value)

    
Output satish python ramesh physics

Exercise on setdefault method

 
      The setdefault() returns:
value of the key if it is in the dictionary
None if key is not in the dictionary and default_value is not specified
default_value if key is not in the dictionary and default_value is specified

di={“chris":"python","ramesh":"physics"}
print(di.setdefault("satish",“notassigned"))

    
Output

Update Method for updating the value for a specific key

 
      di={"satish":"python","ramesh":"physics"}
di2={"test":"testvalue"}
di.update(di2)
print(di)

    
Output {'satish': 'python', 'ramesh': 'physics', 'test': 'testvalue'}

Exercises on Dictionary Comprehension

 
      di={"num1":3,"num2":4,"num3":5}
      Create another dictionary containing  keys whose values are odd numbers
      di2={v:r for (v,r) in di.items() if r%2!=0 }
      print(di2)      

    
Output {'num1': 3, 'num3': 5}

Exercise2 on Dictionary Comprehension

 
      Consider the list given below 
   l=[2,4,5,6,7,8,9]

Create a dictionary using the list(l) such that the output is 
{2: 'even', 4: 'even', 5: 'odd', 6: 'even', 7: 'odd', 8: 'even', 9: 'odd'}

l=[2,4,5,3,7,9]
di2={i:"even" if i%2==0 else "odd" for i in l}
print(di2)

    
Output

Exercise 3 on Dictionary Comprehension

 
      Create another dictionary with names that start with capital letters alone 
di={"name1":"Satish","name2":"Santosh","num3":"sam"}


di2={v:r for (v,r) in di.items() if r[0:1].isupper()}
print(di2)

    
Output {'name1': 'Satish', 'name2': 'Santosh'}

Creating Nested Dictionary

 
      di={"12BCE0001":{"mobile":9976555522,"landline":416222000}}
      print(di) 

    
Output {'12BCE0001': {'mobile': 9976555522, 'landline': 416222000}}

Exercise on Nested Dictionary

 
      di={"12BCE0001":{"mobile":9976555522,"landline":416222000},
    "12BCE0002":{"mobile":8888888888,"landline":416222555}
    }
print(di["12BCE0001"])
print(di["12BCE0002"])

    
Output {'mobile': 9976555522, 'landline': 416222000} {'mobile': 8888888888, 'landline': 416222555}

Printing the Mobile Number for a Specific Student

 
      di={"12BCE0001":{"mobile":9976555522,"landline":416222000},
    "12BCE0002":{"mobile":8888888888,"landline":416222555}
    }
print(di["12BCE0001"]["mobile"])

    
Output 9976555522

Traversing a Nested Dictionary

 
      employee={
        123:{"name":"satish","phone":98777},
        124:{"name":"ramesh","phone":78888}
        }
        
        for item in employee:
            print(item)

    
Output

Printing only name fields from a Nested Dictionary

 
      for item in employee:
      print(employee[item]["name"])
    
Output

Exercise on Dictionary

 
      Read Country and Capital names for n countries as entered by the user. 
If the user searches for a country  then display the country name.
If there is no such country name then display “No Such Country name “ message to the user. 
Use Dictionaries to complete the above task.

    
Output

Solution to the Exercise

 
      num=int(input("Enter the number of countries"))
di={}
flag=0
for i in range(0,num):
    country=input("Enter country name")
    capital=input("Enter capital name")
    di[country]=capital

print(di)
search=input("Enter the search country")
for item in di:
    if item==search:
        print(di[item])
        flag=1
        break

if flag==0:
    print("No such country found")

    
Output